一、题目链接
二、题目分析
(一)算法标签
BFS
(二)解题思路
此题考查BFS
BFS框架见 https://blog.csdn.net/Derrickhang/article/details/123694440
本题整个矩阵(一个数组(字符串))是一个状态,每次扩展到它能到达的状态,同时距离+1,最终看能否找到最终状态
此题出队时判重和入队时判重都可以
详细了解搜索类题目(DFS、BFS),请移步DFS BFS 搜索题目归纳
三、AC代码
解法一:
出队时判重:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>
using namespace std;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int bfs(string start)
{
// 相当于dist数组和st数组
unordered_map<string, int> dist;
dist[start] = 0;
string end = "12345678x";
queue<string> q;
q.push(start);
while (!q.empty())
{
auto t = q.front();
q.pop();
if (t == end) return dist[end];
// x所在字符串的下标
int id = t.find('x');
// x所在矩阵的二维坐标
int x = id / 3, y = id % 3;
// 距离
int distance = dist[t];
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) continue;
int newid = a * 3 + b;
swap(t[newid], t[id]);
// if (t == end) return dist[end];
if (!dist.count(t))
{
dist[t] = distance + 1;
q.push(t);
}
swap(t[newid], t[id]);
}
}
return -1;
}
int main()
{
string start;
char c;
for (int i = 0; i < 9; i ++ )
{
cin >> c;
start += c;
}
cout << bfs(start);
return 0;
}
入队时判重:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>
using namespace std;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int bfs(string start)
{
// 相当于dist数组和st数组
unordered_map<string, int> dist;
dist[start] = 0;
string end = "12345678x";
queue<string> q;
q.push(start);
while (!q.empty())
{
auto t = q.front();
q.pop();
// if (t == end) return dist[end];
// x所在字符串的下标
int id = t.find('x');
// x所在矩阵的二维坐标
int x = id / 3, y = id % 3;
// 距离
int distance = dist[t];
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) continue;
int newid = a * 3 + b;
swap(t[newid], t[id]);
if (!dist.count(t))
{
dist[t] = distance + 1;
q.push(t);
}
if (t == end) return dist[end];
swap(t[newid], t[id]);
}
}
return -1;
}
int main()
{
string start;
char c;
for (int i = 0; i < 9; i ++ )
{
cin >> c;
start += c;
}
cout << bfs(start);
return 0;
}