走迷宫
//距离为1时候常用BFS
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair <int,int> PII;
const int N=110;
int g[N][N],dist[N][N];
int n,m;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int bfs()
{
queue<PII> q;
q.push({0,0});
memset(dist,-1,sizeof dist);
dist[0][0]=0;
int hh=0,tt=0;
while(q.size())
{
auto t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int a=t.x+dx[i],b=t.y+dy[i];
if(a>=0&a<n&&b>=0&&b<m&&g[a][b]==0&&dist[a][b]==-1)
{
dist[a][b]=dist[t.x][t.y]+1;
q.push({a,b});
}
}
}
return dist[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];
}
}
cout<<bfs()<<endl;
return 0;
}
八数码:
//1 2 3 1 2 3 1 2 3 1 2 3
//x 4 6 4 x 6 4 5 6 4 5 6
//7 5 8 7 5 8 7 x 8 7 8 x
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <unordered_map>
using namespace std;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int bfs(string start)
{
queue<string> q;
unordered_map<string,int> d;
q.push(start);
d[start]=0;
string end="12345678x";
while(q.size())
{
auto t=q.front();
q.pop();
if(t==end) return d[t];
int distance=d[t];
int k=t.find('x');
int x=k/3,y=k%3;//一维坐标转二维寻早x的位置
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[a*3+b],t[k]);//二维转一维,交换X和下一个可以走的位置
if(!d.count(t))
{
d[t]=distance+1;
q.push(t);
}
swap(t[a*3+b],t[k]);//恢复现场
}
}
}
return -1;
}
int main()
{
string start;
for(int i=0;i<9;i++)
{
char c;
cin>>c;
start+=c;
}
cout<<bfs(start)<<endl;
return 0;
}