Appoint description:
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,
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
#include
#include
#include
using namespace std;
int a[10][10];
struct node
{
int x,y,tep;
};
node b[10][10];
queue
Q; int bfs() { int i,j; int x[]= {1,0,0,-1}; int y[]= {0,1,-1,0}; node xx,yy; while(!Q.empty()) Q.pop(); xx.tep=0; xx.y=xx.x=4; Q.push(xx); a[4][4]=1; while(!Q.empty()) { xx=Q.front(); Q.pop(); yy.tep=xx.tep+1; for(i=0; i<4; i++) { yy.x=xx.x+x[i]; yy.y=xx.y+y[i]; if(yy.x>=0&&yy.x<5&&yy.y>=0&&yy.y<5&&a[yy.x][yy.y]==0) { b[yy.x][yy.y].x=xx.x; b[yy.x][yy.y].y=xx.y; if(yy.x==0&&yy.y==0) return yy.tep; a[yy.x][yy.y]=1; Q.push(yy); } } } } int main() { int i,j,ans,x,y,xx,yy; for(i=0; i<5; i++) { for(j=0; j<5; j++) { scanf("%d",&a[i][j]); } } ans=bfs(); x=y=0; for(i=0; i<=ans; i++) { printf("(%d, %d)\n",x,y); xx=b[x][y].x; yy=b[x][y].y; x=xx; y=yy; } return 0; }