Maze Problems
| Time limit:1000 ms |
|
Memory limit:65536 K |
| Total submissions:7560 |
|
Accepted:4426 |
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, where 1 represents a wall, 0 represents a path that can be taken, and can only walk horizontally or vertically, not diagonally, the program is required to find the shortest route from the upper left corner to the lower right corner.
Input
A 5 × 5 Two-dimensional array represents a maze. The data guarantee has a unique solution.
Output
The shortest path from the upper left corner to the lower right corner, as shown in the example.
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)
Meaning .. I have already told you the question ..
You just need to use the search record path ..
#include<algorithm>#include<iostream>#include<cstring>#include<cstdio>#include<vector>#include<queue>#include<cmath>using namespace std;int map[6][6];int dx[] = {-1, 0, 0, 1};int dy[] = {0, -1, 1, 0};int pre[30];struct node{ int x; int y;};node path[30];void output(int head){ int tmp = pre[head]; if(tmp==0) printf("(%d, %d)\n", path[tmp].x, path[tmp].y); else output(tmp); printf("(%d, %d)\n", path[head].x, path[head].y);}void bfs(){ int head = 0; int tail = 1; pre[head] = -1; path[head].x = 0; path[head].y = 0; map[ path[head].x][path[head].y ] = 1; while(head<tail) { int x = path[head].x; int y = path[head].y; if(x==4 && y==4) { output(head); return ; } for(int i=0;i<4;i++) { int xx = x + dx[i]; int yy = y + dy[i]; if(map[xx][yy]==0 && xx>=0 && xx<5 && yy>=0 && yy<5 ) { map[xx][yy]=1; path[tail].x = xx; path[tail].y = yy; pre[tail] = head; tail++; } } head++; }}int main(){ int i,j; for(i=0;i<5;i++) for(j=0;j<5;j++) scanf("%d",&map[i][j]); bfs(); return 0;}
There is also a way to write .. It's just someone else's... Orz...
# Include <iostream> # include <queue> using namespace STD; int A [5] [5]; int dir [4] [2] =, 0,-1}; int map [5] [5]; void BFS (int x, int y) {queue <int> q; q. push (x); q. push (y); While (! Q. empty () {int M = Q. front (); q. pop (); int n = Q. front (); q. pop (); For (INT I = 0; I <4; I ++) {int Mm = m + dir [I] [1]; int nn = N + dir [I] [0]; If (Mm = 4 & nn = 4) {map [mm] [NN] = m * 5 + N; return ;} if (MM> = 0 & mm <= 4 & NN> = 0 & NN <= 4 & A [mm] [NN]! = 1) {q. push (mm); q. push (NN); map [mm] [NN] = (5 * m + n ); // A [mm] [NN] = 1 ;}}} void print (int I, Int J) {if (I = 0 & J = 0) {printf ("(0, 0)/n"); return ;} print (Map [I] [J]/5, map [I] [J] % 5); printf ("(% d, % d)/n", I, j) ;}int main () {for (INT I = 0; I <5; I ++) {for (Int J = 0; j <5; j ++) {CIN> A [I] [J] ;}} BFS (0, 0); print (4, 4); Return 0 ;}
Poj 3984: Maze problem (BFS + path record)