定义一个二维数组:
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
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)【代码】
#include<iostream> #include<cstring> #include<cstdio> using namespace std; int sx[4]={1,-1,0,0}; int sy[4]={0,0,1,-1}; int head,tail,nowx,nowy,x,y; struct hp{ int x,y,pre; }queue[105]; int a[10][10]; bool b[10][10]; inline void print(int find){ if (queue[find].pre) print(queue[find].pre); printf("(%d, %d)\n",queue[find].x-1,queue[find].y-1); } int main(){ for (int i=1;i<=5;++i) for (int j=1;j<=5;++j) scanf("%d",&a[i][j]); head=0; tail=1; queue[tail].x=1,queue[tail].y=1,queue[tail].pre=0; while (head<tail){ ++head; nowx=queue[head].x,nowy=queue[head].y; for (int i=0;i<4;++i){ x=sx[i]+nowx,y=sy[i]+nowy; if (x>0&&x<=5&&y>0&&y<=5&&!a[x][y]&&!b[x][y]){ tail++; b[x][y]=true; queue[tail].x=x,queue[tail].y=y,queue[tail].pre=head; if (x==5&&y==5) {print(tail); return 0;} } } } }