Define a two-dimensional array:
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, };
It represents a labyrinth, in which 1 represents the wall and 0 represents the path that can be taken. It can only walk horizontally or vertically, but not obliquely. It requires programming to find the shortest path from the upper left corner to the lower right corner.
Input
A 5*5 two-dimensional array representing a maze. The data guarantees a unique solution.
Output
The shortest path from the upper left corner to the lower right corner is shown as an example.
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)
Structures with string s are used to record the direction of movement.
#include<cstdio> #include<string> #include<string.h> #include<queue> #include<iostream> using namespace std; const int N=6; int s[N][N],vis[N][N]; int e=5; int dir[4][2]={0,-1,1,0,-1,0,0,1}; //DRLU Records Moving Direction struct node{ int x,y,step; string pas; }now,nex; bool check(int x,int y){ if(s[x][y]==0&&x>0&&x<6&&y>0&&y<6&&!vis[x][y]){ vis[x][y]=1; return true; } return false; } void prt(string t){//Print path int len=t.length() ; int x=0 ,y=0 ; cout<<"(0, 0)"<<endl; for(int i=0;i<len;++i){ switch( t[i]){ case 'D':{ printf("(%d, %d)\n",x,y-1); y--; break; } case 'R':{ printf("(%d, %d)\n",x+1,y); x++; break; } case 'L':{ printf("(%d, %d)\n",x-1,y); x--; break; } default:{ printf("(%d, %d)\n",x,y+1); y++; break; } } } } void bfs(){ queue<node>que; while(!que.empty()) que.pop(); now.step =0,now.x =1,now.y =1,now.pas =""; que.push(now); while(!que.empty()){ nex=que.front(); que.pop(); if(nex.x ==5&&nex.y ==5){ prt(nex.pas ); } for(int i=0;i<4;++i){ int dx=nex.x +dir[i][0],dy=nex.y +dir[i][1]; now.step =nex.step +1; now.x =dx; now.y =dy; switch(i){ case 0:{; if(check(dx,dy)){ now.pas =nex.pas +'D'; que.push(now); } break; } case 1:{ if(check(dx,dy)){ now.pas =nex.pas +'R'; que.push(now); } break; } case 2:{ if(check(dx,dy)){ now.pas =nex.pas +'L'; que.push(now); } break; } default:{ if(check(dx,dy)){ now.pas =nex.pas +'U'; que.push(now); } break; } } } } } int main(){ for(int i=1;i<=5;++i){ for(int j=1;j<=5;++j){ scanf("%d",&s[i][j]); } } bfs(); return 0; }