BFS 两种:
1.网格从一个点出发走到某个点 需要的最少步数
2.一整个网格状态变为另一种网格状态 需要的最少步数
共同关键:明确下一个将变化的状态是由哪一个状态变化来的
第一种 洛谷 P6207
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 125;
int n,m;
char g[N][N];
bool st[N][N];
queue<PII> q;
PII pre[N][N];
vector<PII> trac;
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
void bfs(int sx,int sy)
{
st[sx][sy] = true;
q.push({sx,sy});
while(q.size())
{
auto t = q.front();
q.pop();
int a = t.first,b = t.second;
for(int i = 0;i < 4;i++)
{
int x = a + dx[i],y = b + dy[i];
if(x < 0 || x >= n || y < 0 || y >= m) continue;
if(st[x][y] || g[x][y] == '*') continue;
st[x][y] = true;
q.push({x,y});
pre[x][y] = t; // 从当前的点t 可以走到的下一个点(x,y)
}
}
int x = n - 1,y = m - 1;
while(x || y) // 直到起点 (0,0)
{
trac.push_back({x + 1,y + 1});
auto t = pre[x][y]; // 此处 auto 为 PII 之前错误理解:不是自动推断为迭代器 ::iterator
x = t.first,y = t.second; // 不断往前 回溯
}
}
int main()
{
cin >> n >> m;
for(int i = 0;i < n;i++) scanf("%s",g[i]);
bfs(0,0);
printf("1 1\n");
for(int i = trac.size() - 1;i >= 0;i--)
printf("%d %d\n",trac[i].first,trac[i].second);
return 0;
}
第二种 牛客 NC51032
#include <bits/stdc++.h>
using namespace std;
const int N = 15;
string start;
unordered_map<string,string> d;
queue<string> q;
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
char dc[4] = {'u','r','d','l'};
string bfs()
{
string end = "12345678x";
q.push(start);
d[start] = "";
while(q.size())
{
auto t = q.front();
q.pop();
string s = d[t];
if(t == end) return s;
int k = t.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) continue;
swap(t[k],t[a * 3 + b]);
if(!d.count(t))
{
d[t] = s + dc[i]; // 存路径的关键 明确下一个串是由哪一个串 变化过来的
q.push(t); // 同上一个模型 明确下一个点是由哪个点 变化过来的
}
swap(t[k],t[a * 3 + b]);
}
}
return "";
}
int main()
{
for(int i = 0;i < 9;i++)
{
char c;
cin >> c;
start += c;
}
cout << bfs() << endl;
return 0;
}