定義一個二維數組:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一個迷宮,其中的1表示牆壁,0表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。
Input
一個5 × 5的二維數組,表示一個迷宮。數據保證有唯一解。
Output
左上角到右下角的最短路徑,格式如樣例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
利用隊列進行廣搜,不讓求步數,但是要記錄路徑;
#include<iostream>
#include<queue>
using namespace std;
int vis[6][6],mp[6][6];
struct node {
int x,y;
} pre[10][10];
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
void bfs(node a) {
queue<node> q;
node b,c;
q.push(a);
vis[a.x][a.y]=1;
while(!q.empty()) {
b=q.front();
q.pop();
if(b.x==4&&b.y==4){
return;
}
for(int i=0; i<4; i++) {
c.x=b.x+dir[i][0];
c.y=b.y+dir[i][1];
if(!vis[c.x][c.y]&&(c.x>=0&&c.x<5)&&(c.y>=0&&c.y<5)) {
q.push(c);
pre[c.x][c.y].x=b.x;
pre[c.x][c.y].y=b.y;//此步記錄c的上一個點是b
vis[c.x][c.y]=1;
}
}
}
}
void print(int x,int y) {//遞歸倒着打印
if(x==0&&y==0) {
printf("(0, 0)\n");
return;
} else
print(pre[x][y].x,pre[x][y].y);
printf("(%d, %d)\n",x,y);
}
int main() {
for(int i=0; i<5; i++)
for(int j=0; j<5; j++) {
scanf("%d",&mp[i][j]);
{
if(mp[i][j]==1)
vis[i][j]=1;
}
}
node a;
a.x=0,a.y=0;
bfs(a);
print(4,4);
return 0;
}
深搜代碼:
#include<iostream>
using namespace std;
int pre[10][10],mp[6][6];
int vis[10][10];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
struct node{
int x,y;
}a[10][10];
void dfs(int x,int y){
if(x==4&&y==4){
return ;
}
for(int i=0;i<4;i++){
int tx=x+dir[i][0];
int ty=y+dir[i][1];
if(tx<0||tx>4||ty<0||ty>4||vis[tx][ty]==1) continue;
vis[tx][ty]=1;
a[tx][ty].x=x;
a[tx][ty].y=y;
dfs(tx,ty);
}
}
void print(int x,int y){
if(x==0&&y==0){
printf("(%d, %d)\n",x,y);
return;
}
print(a[x][y].x,a[x][y].y);
printf("(%d, %d)\n",x,y);
}
int main(){
for(int i=0;i<5;i++)
for(int j=0;j<5;j++){
cin>>mp[i][j];
if(mp[i][j]==1) vis[i][j]=1;
}
dfs(0,0);
print(4,4);
}