绝对经典!
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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)
方法一:
<pre name="code" class="cpp">#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <queue> using namespace std; struct Node { int x,y; }node[30]; int father[30],map[5][5],vis[5][5]; int xx[4]={1,-1,0,0}; int yy[4]={0,0,1,-1}; queue<Node>q; void printf_1() { int a[30]; //printf("(0, 0)\n"); int u=24; int j=0; while(1) { a[j++]=father[u]; u=father[u]; if(u==0) break; } //printf("(0, 0)\n"); for(int i=j-1;i>=0;i--) printf("(%d, %d)\n",a[i]/5,a[i]%5); printf("(4, 4)\n"); } void bfs(int x,int y) { memset(vis,0,sizeof(vis)); memset(father,-1,sizeof(father)); vis[0][0]=1; Node now,next; now.x=0,now.y=0; //father[x*5+y]=0; q.push(now); while(!q.empty()) { now=q.front(); q.pop(); for(int i=0;i<4;i++) { int dx=now.x+xx[i]; int dy=now.y+yy[i]; if(dx>=0&&dx<=4&&dy>=0&&dy<=4&&vis[dx][dy]==0&&map[dx][dy]==0) { vis[dx][dy]=1; father[dx*5+dy]=now.x*5+now.y; if(dx==4&&dy==4) { printf_1(); return ; } next.x=dx; next.y=dy; q.push(next); } } } } int main () { for(int i=0;i<=4;i++) for(int j=0;j<=4;j++) scanf("%d",&map[i][j]); bfs(0,0); return 0; }
方法二:模拟队列
<pre name="code" class="cpp">#include <iostream> #include <string.h> #include <fstream> using namespace std; struct node { int x; int y; int pre; }edge[100]; int front = 0, rear = 1; //队头,队尾 int map[5][5]; int vis[5][5]; int d[4][2] = {{1,0},{0,-1},{-1,0},{0,1}}; void PrePath(int i) { //倒向追踪法 if(edge[i].pre != -1) { PrePath(edge[i].pre); cout<<"("<<edge[i].x<<", "<<edge[i].y<<")"<<endl; } } void bfs(int x1, int y1, int x2, int y2) { edge[front].x = x1; edge[front].y = y1; edge[front].pre = -1; while(front < rear) { //队列为空时终止 for(int u = 0; u < 4; u++) { int x = edge[front].x + d[u][0]; int y = edge[front].y + d[u][1]; if((x < 0) || (x >= 5) || (y < 0) || (y >= 5) || (map[x][y] == 1) || (vis[x][y] == 1)) { continue; } else { vis[x][y] = 1; map[x][y] = 1; edge[rear].x = x; //入队 edge[rear].y = y; edge[rear].pre = front; rear++; } if(x == x2 && y == y2) { PrePath(front); } } front++; //出队 } } int main() { freopen("C:\\Users\\HZH\\Desktop\\input.txt","r",stdin); memset(vis, 0, sizeof(vis)); for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { cin>>map[i][j]; } } int x1,x2,y1,y2; cin>>x1>>y1>>x2>>y2; fclose(stdin); cout<<"("<<x1<<", "<<y1<<")"<<endl; bfs(x1, y1, x2, y2); cout<<"("<<x2<<", "<<y2<<")"<<endl; }