Maze Problems
| Time limit:1000 ms |
|
Memory limit:65536 K |
| Total submissions:7635 |
|
Accepted:4474 |
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)
Source
Guang Suo, entry question.
Question:
Give you a 5*5 maze. 0 represents the path, 1 represents the wall, find the shortest path from the upper left corner of the maze to the lower right corner, and output the path.
Ideas:
This question is a simple broad search question. Why is it a wide search? Because the question is to find the shortest path, such questions are basically widely searched. However, unlike other steps that directly output the shortest path, this question outputs the shortest path and outputs the path. Therefore, we need to consider the status, each status should store the path to this status. There is nothing else to say. In general, it is a relatively simple broad search entry question.
Code:
1 # include <iostream> 2 # include <stdio. h> 3 # include <string. h> 4 # include <queue> 5 using namespace STD; 6 7 bool ISW [5] [5]; 8 int A [5] [5]; 9 int DX [4] = {, 0,-1}; 10 int dy [4] = {,-}; 11 12 struct node {13 int X; 14 int y; 15 int s; 16 short L [30]; 17}; 18 19 bool judge (int x, int y) 20 {21 if (x <0 | x> = 5 | Y <0 | Y> = 5) 22 return true; 23 if (ISW [x] [Y]) 24 return true; 25 if (a [x] [Y] = 1) 26 return true; 27 return false; 28} 29 30 node BFS () 31 {32 queue <node> q; 33 node cur, next; 34 cur. X = 0; 35 cur. y = 0; 36 cur. S = 0; 37 ISW [cur. x] [cur. y] = true; 38 Q. push (cur); 39 while (! Q. empty () {40 cur = Q. front (); 41 Q. pop (); 42 if (cur. X = 4 & cur. y = 4) 43 return cur; 44 int I, NX, NY; 45 for (I = 0; I <4; I ++) {46 Nx = cur. X + dx [I]; 47 ny = cur. Y + dy [I]; 48 if (Judge (NX, NY) 49 continue; 50 // 51 next = cur; 52 next. X = NX; 53 next. y = NY; 54 next. S = cur. S + 1; 55 next. L [cur. s] = I; 56 Q. push (next); 57} 58} 59 return cur; 60} 61 62 63 int main () 64 {65 int I, j; 66 for (I = 0; I <5; I ++) {// read the maze 67 for (j = 0; j <5; j ++) {68 scanf ("% d ", & A [I] [J]); 69} 70} 71 memset (ISW, 0, sizeof (ISW); 72 node ans = BFS (); 73 int X, y; 74 x = 0, y = 0; 75 for (I = 0; I <= ans. s; I ++) {76 printf ("(% d, % d) \ n", x, y); 77 x + = DX [ans. L [I]; 78 y + = Dy [ans. L [I]; 79} 80 return 0; 81}
Freecode: www.cnblogs.com/yym2013