0pts求调
查看原帖
0pts求调
1044126
HaloCode楼主2025/1/12 11:48
#include<bits/stdc++.h>
using namespace std;
struct PII {
	int x, y;
};
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
string first, endd = "123804765";

//get_coord函数可以返回字符串s所构成的矩阵中0的坐标
PII get_coord(string s) {
	for (int i = 0; i < 9; i++) {
		if (s[i] == '0') {
			return {i / 3, i % 3};
		}
	}
}

int second_bfs(queue<string> &q, unordered_map<string, int> &mp1, unordered_map<string, int> &mp2) {
	string u = q.front();
	q.pop();
	PII st = get_coord(u);
	for (int i = 0; i < 4; i++) {
		PII v;
		v.x = st.x + dx[i];
		v.y = st.y + dy[i];
		//判断是否越界
		if (v.x < 0 || v.x > 3 || v.y < 0 || v.y > 3) {
			continue;
		}
		string p = u;
		swap(p[st.x * 3 + st.y], p[v.x * 3 + v.y]);
		if (mp2.count(p) == 1) {
			return mp2[p] + 1;
		}
		if (mp1.count(p) == 1) {
			continue;
		}
		mp1[p] = mp1[u] + 1;
		q.push(p);
	}
	return -1;	//没有找到
}

int bfs() {
	queue<string> qstart, qend;
	unordered_map<string, int> mp1, mp2;
	qstart.push(first);
	qend.push(endd);
	mp1[first] = 0;	//起点到自己的距离为0
	mp2[endd] = 0;

	while (qstart.size() && qend.size()) {
		int ans = 0;
		if (qstart.size() < qend.size()) {
			ans = second_bfs(qstart, mp1, mp2);
		} else {
			ans = second_bfs(qend, mp2, mp1);
		}
		if (ans != -1) {
			return ans;
		}
	}

	return -1;
}

int main() {
	cin >> first;
	//特判,如果相等
	if (first == endd) {
		cout << 0;
	}

	cout << bfs();
	return 0;
}
2025/1/12 11:48
加载中...