#include<iostream>#include<cstring>#include<algorithm>
using namespace std;constint N =110;typedef pair<int,int> PII;int n, m;int g[N][N];//存放地图int d[N][N];//存 每一个点到起点的距离
PII q[N * N];//手写队列intbfs(){int hh =0, tt =0;
q[0]={0,0};memset(d,-1,sizeof d);//距离初始化为- 1表示没有走过
d[0][0]=0;//表示起点走过了int dx[4]={-1,0,1,0}, dy[4]={0,1,0,-1};//x 方向的向量和 y 方向的向量组成的上、右、下、左while(hh <= tt)//队列不空{
PII t = q[hh ++];//取队头元素for(int i =0; i <4; i ++)//枚举4个方向{int x = t.first + dx[i], y = t.second + dy[i];//x表示沿着此方向走会走到哪个点if(x >=0&& x < n && y >=0&& y < m && g[x][y]==0&& d[x][y]==-1)//在边界内 并且是空地可以走 且之前没有走过{
d[x][y]= d[t.first][t.second]+1;//到起点的距离
q[++ tt ]={x, y};//新坐标入队}}}return d[n -1][m -1];//输出右下角点距起点的距离即可}intmain(){
cin >> n >> m;for(int i =0; i < n; i ++)for(int j =0; j < m; j ++)
cin >> g[i][j];
cout <<bfs()<< endl;return0;}
2.队列
#include<iostream>#include<cstring>#include<queue>usingnamespace std;constint N =110;typedef pair<int,int> PII;int n, m;int g[N][N], d[N][N];intbfs(){
queue< pair<int,int>> q;
q.push({0,0});memset(d,-1,sizeof(d));
d[0][0]=0;int dx[4]={-1,0,1,0}, dy[4]={0,1,0,-1};while(q.size())//队列不为空{
PII t = q.front();//取队头元素
q.pop();//出队for(int i =0; i <4; i++){int x = t.first + dx[i], y = t.second + dy[i];if(x >=0&& x < n && y >=0&& y < m && g[x][y]==0&& d[x][y]==-1){
d[x][y]= d[t.first][t.second]+1;//当前点到起点的距离
q.push({x, y});//将新坐标入队}}}return d[n -1][m -1];}intmain(){
cin >> n >> m;for(int i =0; i < n; i++)for(int j =0; j < m; j++)
cin >> g[i][j];
cout <<bfs()<< endl;return0;}
3.打印路径
#include<iostream>#include<cstring>#include<algorithm>
using namespace std;constint N =110;typedef pair<int,int> PII;
PII q[N*N],Prev[N][N];int g[N][N], d[N][N];int n, m;intbfs(){int hh =0, tt =0;
q[0]={0,0};memset(d,-1,sizeof d);int dx[4]={-1,0,1,0}, dy[4]={0,1,0,-1};
d[0][0]=0;while(hh <= tt){
PII t = q[hh ++];for(int i =0; i <4; i ++){int x = dx[i]+ t.first, y = t.second + dy[i];if(x >=0&& x < n && y >=0&& y < m && g[x][y]==0&& d[x][y]==-1){
d[x][y]= d[t.first][t.second]+1;
Prev[x][y]= t;
q[++ tt]={x, y};}}}int x = n -1, y = m -1;while(x || y)//有一个不d等于0{
cout << x <<' '<< y << endl;
PII t = Prev[x][y];
x = t.first, y = t.second;}return d[n -1][m -1];}intmain(){
cin >> n >> m;for(int i =0; i < n; i ++)for(int j =0; j < m;j ++)
cin >> g[i][j];
cout <<bfs()<< endl;return0;}