...11111111111111111111111111111
11.111111........1111111111.1111
11.111111..111.11111111.....1111
11.11111111111.1111111111.111111
11.111111.................111111
11.111111.11111111111.11111.1111
11.111111.11111111111.11111..111
11..........111111111.11111.1111
11111.111111111111111.11....1111
11111.111111111111111.11.11.1111
11111.111111111111111.11.11.1111
111...111111111111111.11.11.1111
111.11111111111111111....11.1111
111.11111111111111111111111.1111
111.1111.111111111111111......11
111.1111.......111111111.1111.11
111.1111.11111.111111111.1111.11
111......11111.111111111.1111111
11111111111111.111111111.111...1
11111111111111...............1.1
111111111111111111111111111111..
如上图的迷宫,入口,出口分别:左上角,右下角
"1"是墙壁,"."是通路
求最短需要走多少步?
思路:求最短路径的一般就是bfs了,直接广度优先搜索。
#include<iostream>
#include<queue>
using namespace std;
#define maxn 50
char maze[maxn][maxn];
bool visit[maxn][maxn];
int step[maxn][maxn];
int fx[]={0,0,1,-1};
int fy[]={1,-1,0,0};
queue<int> qx;
queue<int> qy;
int row=0,col=0;
bool Inter(int x,int y){
if(x<row&&x>=0&&y<col&&y>=0)return true;
return false;
}
void bfs(int i,int j){
visit[i][j]=true;
step[i][j]=1;
qx.push(i);
qy.push(j);
while(!qx.empty()){
int nowx=qx.front();
int nowy=qy.front();
if(nowx==row-1&&nowy==col-1){
cout<<step[nowx][nowy]<<endl;
return;
}
int newx;
int newy;
for(int k=0;k<4;k++){
newx=nowx+fx[k];
newy=nowy+fy[k];
if(Inter(newx,newy)&&!visit[newx][newy]&&maze[newx][newy]=='.'){
qx.push(newx);
qy.push(newy);
step[newx][newy]=step[nowx][nowy]+1;//步数等于上一步加1。
visit[newx][newy]=true;
}
}
qx.pop();
qy.pop();
}
}
int main(){
int i=0,j=0;
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
while(gets(maze[row++]));
row=row-1; //得出迷宫的行数
while(maze[i][j++]!='\0')col++;//得出迷宫的列数。
bfs(0,0);
return 0;
}