问题 B: 八数码问题–搜索树(BFS)
时间限制: 1 Sec 内存限制: 128 MB
题目描述
在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字。棋盘中留有一个空格,空格用0来表示。空格周围的棋子可以移到空格中。
给出一种初始状态S0和目标状态Sg,请找到一种最少步骤的移动方法,实现从初始状态S0到目标状态Sg的转变。
输入
输入测试次数 t
对于每次测试,首先输入一个初始状态S0,一行九个数字,空格用0表示。然后输入一个目标状态Sg,一行九个数字,空格用0表示。
输出
只有一行,该行只有一个数字,表示从初始状态S0到目标状态Sg需要的最少移动次数(测试数据中无特殊无法到达目标状态数据)
样例输入
2
283104765
123804765
283104765
283164705
样例输出
4
1
AC代码
#include<bits/stdc++.h>
using namespace std;
int main() {
map<int, set<int>>go_next;
go_next[0] = { 1,3 };
go_next[1] = { 0,2,4 };
go_next[2] = { 1,5 };
go_next[3] = { 0,4,6 };
go_next[4] = { 1,3,5,7 };
go_next[5] = { 2,4,8 };
go_next[6] = { 3,7 };
go_next[7] = { 4,6,8 };
go_next[8] = { 5,7 };
int n;
cin >> n;
while (n--)
{
map<string, int>depth;
string start, end;
cin >> start >> end;
queue<string>search_queue;
string cur_node;
search_queue.push(start);
while (!search_queue.empty())
{
cur_node = search_queue.front();
search_queue.pop();
if (cur_node == end)
break;
int pos = cur_node.find('0');
for (auto it = go_next[pos].begin(); it != go_next[pos].end(); it++)
{
string new_node = cur_node;
swap(new_node[pos], new_node[*it]);
if (depth.find(new_node) != depth.end())
continue;
search_queue.push(new_node);
depth[new_node] = depth[cur_node] + 1;
}
}
cout << depth[cur_node] << endl;
}
return 0;
}