BFS八数码问题:
#include <iostream> #include <cstring> #include <queue> #include <unordered_map> using namespace std; int bfs(string start) { string end = "12345678x"; queue<string> q; unordered_map<string, int>d; q.push(start); d[start] = 0; int dx[4] = {-1,1,0,0},dy[4] = {0,0,1,-1}; while(!q.empty()) { string s = q.front(); q.pop(); int distance = d[s]; if(s == end) return distance; int k = s.find('x'); int x = k / 3, y = k % 3; for(int i = 0;i<4;i++) { int a = x + dx[i], b = y + dy[i]; if(a >= 0 && a < 3 && b >= 0 && b < 3) { swap(s[k],s[a*3+b]); if(!d.count(s)) { d[s] = distance + 1; q.push(s); } swap(s[k],s[a*3+b]); } } } return -1; } int main() { string start; cin>>start; cout<<bfs(start)<<endl; }
注意:d.count(s)表示unordered_map类型的d键对应值的数量