迷宫问题
链接: ACWing 844
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 200;
int g[N][N],f[N][N];
int m, n;
int dx[5] = {1,-1,0,0} , dy[5] = {0,0,-1,1};
void bfs(int a, int b){
queue<PII> q;
q.push({a,b});
while (!q.empty()){
PII start = q.front();
q.pop();
g[start.first][start.second] = 1;
for (int i = 0; i < 4; i ++){
int x = start.first + dx[i], y = start.second + dy[i];
if (!g[x][y] && x>= 0 && x < n && y >= 0 && y < m){
g[x][y] = 1;
f[x][y] = f[start.first][start.second] + 1;
q.push({x,y});
}
}
}
cout << f[n-1][m-1];
}
int main(){
cin >> n >> m;
for (int i = 0; i < n; i ++)
for (int j = 0; j < m; j ++)
cin >> g[i][j];
bfs(0,0);
return 0;
}
八数码
链接: ACWing 845
# include <bits/stdc++.h>
using namespace std;
int dx[5] = {1,-1,0,0} , dy[5] = {0,0,-1,1};
queue<string> q;
unordered_map<string,int> d;
int bfs(string start){
q.push(start);
string end = "12345678x";
d[start] = 0;
while(!q.empty()){
string t = q.front();
q.pop();
//记录当前状态的距离,如果是最终状态则返回距离
int distance = d[t];
if (t == end) return distance;
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){
swap(t[k],t[3*a + b]);
if (!d.count(t)){
d[t] = distance + 1;
q.push(t);
}
/*一种状态有四种不同的转换情况(上、下、左、右),循环中需要遍历所有四种情况。
这个地方是直接改变的原本状态,所以每一次循环结束要还原状态,“下一种情况“就是”上下左右“中的某一种*/
swap(t[k],t[a*3+b]);
}
}
}
return -1;
}
int main(){
string op,start;
for (int i = 0; i < 9; i ++){
cin >> op;
start += op;
}
cout << bfs(start);
}