Description
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, };
Input
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<cstdio> #include<queue> using namespace std; int map[6][6]; int dx[]={0,1,-1,0}; int dy[]={1,0,0,-1}; struct move { int x,y; int pre; }q[150],pos; void Print_Result(int pre) { if(q[pre].pre!=-1)//有点像找根节点,找到了再输出 { Print_Result(q[pre].pre); printf("(%d, %d)\n",q[pre].x,q[pre].y); } } void BFS() { int front=0,rear=1; q[front].pre=-1; q[front].x=0; q[front].y=0; map[0][0]=1; while(front<rear) { for(int j=0;j<4;++j) { int a=q[front].x+dx[j]; int b=q[front].y+dy[j]; if(a<0||a>=5||b<0||b>=5||map[a][b]) continue; if(a==4&&b==4) { Print_Result(front); return ; } map[a][b]= 1; q[rear].x=a; q[rear].y=b; q[rear].pre=front; rear++; } front++; } } int main() { for(int i=0;i<5;++i) { for(int j=0;j<5;++j) scanf("%d",map[i]+j); } printf("(0, 0)\n"); BFS(); printf("(4, 4)\n"); return 0; }