Maze Problems
Time limit:1000 ms |
|
Memory limit:65536 K |
Total submissions:35426 |
|
Accepted:20088 |
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)
Question: Give a maze matrix and output a path
Problem: DFS finds a path and uses the stack record (poj uses the universal header file to associate ce Emmmm)
1 # include <cstdio> 2 # include <cstring> 3 # include <string> 4 # include <cmath> 5 # include <iostream> 6 # include <algorithm> 7 # include <map> 8 # include <set> 9 # include <queue> 10 # include <vector> 11 # include <stack> 12 using namespace STD; 13 int A [20] [20]; 14 const int n = 5; 15 stack <pair <int, int> STK; 16 bool DFS (int I, Int J) {17 if (I = n-1 & J = N-1) {18 STK. push (make_pair (I, j); 19 Return true; 20} 21 if (I> = 0 & I <= n-1 & J> = 0 & J <= n-1) {// determine the boundary 22 if (a [I] [J] = 0) {// you can leave without passing through 23 A [I] [J] = 1; // 24 if (DFS (I, j + 1) | DFS (I + 1, J) | DFS (I, j-1) | DFS (I-1, J) {// go to 25 STK. push (make_pair (I, j); 26 return true; 27} else {// backtracking 28 A [I] [J] = 0; 29 return false; 30} 31} else {32 return false; 33} 34} else {35 return false; 36} 37} 38 int main () {39 for (INT I = 0; I <5; I ++) {40 for (Int J = 0; j <5; j ++) {41 scanf ("% d", & A [I] [J]); 42} 43} 44 DFS (0, 0 ); 45 while (! STK. empty () {46 printf ("(% d, % d) \ n", STK. top (). first, STK. top (). second); 47 STK. pop (); 48} 49 return 0; 50}
Poj3984 Maze problem (DFS + stack)