POJ 3984 bfs+ Backtracking path Maze problem
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 9218 |
|
Accepted: 5459 |
Description
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 maze, of which 1 represents a wall, 0 means that the road can be walked, can only walk sideways or vertical walk, can not be inclined to walk, asked to compile the program to find the shortest route from the upper left to the lower right corner.
Input
A 5x5 two-dimensional array that represents a maze. The data guarantee has a unique solution.
Output
The shortest path in the upper-left corner to the lower-right corner, formatted as shown in the sample.
Sample Input
0 1 0 0 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
Find a water problem to relax ... Wrote for more than 10 minutes ...
/*poj3984 0ms*/#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>#include<vector>#include<queue>#include<stack>using namespacestd;Const intmaxn= -;Const intInf= (1<< -);Const intn=5;BOOLVIS[MAXN][MAXN];structnode{intx, y; intDist;}; Node FA[MAXN][MAXN];intdx[]={-1,1,0,0};intdy[]={0,0,-1,1};BOOLBFs () {Queue<node>Q; Q.push ({1,1,0}); vis[1][1]=1; fa[1][1]={0,0}; while(!Q.empty ()) {Node now=Q.front (); Q.pop (); if(now.x==5&&now.y==5)return true; for(intI=0;i<4; i++){ intnx=now.x+Dx[i]; intny=now.y+Dy[i]; intnd=now.dist+1; if(Vis[nx][ny])Continue; Vis[nx][ny]=1; Fa[nx][ny]=Now ; Q.push ({nx,ny,nd}); } } return false;}voidPrintpath () {stack<node>path; Node now={5,5}; while(now.x&&now.y) {Path.push (now); now=FA[NOW.X][NOW.Y]; } while(!Path.empty ()) {printf ("(%d,%d) \ n", Path.top (). x1, Path.top (). Y1); Path.pop (); }}intMain () {memset (Vis,1,sizeof(VIS)); for(intI=1; i<=n;i++){ for(intj=1; j<=n;j++) {cin>>Vis[i][j]; } } if(BFS ())) Printpath (); Elseprintf"error\n"); return 0;}
Poj3984_bfs
poj3984_bfs+ Backtracking Path