AC 后的一点疑问
查看原帖
AC 后的一点疑问
581830
Jasper08楼主2022/7/17 23:28

朴素 bfs. 核心代码:

int hh = 0, tt = 1;
int a[4] = {-1, 0, 1, 0}, b[4] = {0, 1, 0, -1};
unordered_map<string, int> dis;
string q[N*N];

int bfs(string start) {
	string end = "123804765";
	q[0] = start;
	dis[start] = 0;
	
	while (hh <= tt) {
		string t = q[hh ++];
		
		if (t == end)
			return dis[t];
		
		int d = dis[t];
		int k = t.find('0');
		int xc = k/3, yc = k%3;
		for (int i = 0; i < 4; ++i) {
			int x = xc+a[i], y = yc+b[i];
			if (x >= 0 && x < 3 && y >= 0 && y < 3) {
				swap(t[x*3+y], t[k]);
				if (!dis.count(t)) {
					dis[t] = d+1, q[tt ++] = t;
					//cout << t << " " << dis[t] << endl;
				}
				swap(t[x*3+y], t[k]);
			}
		}
	}
	
	return -1;
}

想知道为什么 tt 要初始化成 1,而不能初始化成 0(不然连样例都过不去 qwq)

2022/7/17 23:28
加载中...