Maze Problems
Time Limit: 1000 MS Memory Limit: 65536 K
Total Submissions: 6322 Accepted: 3673
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 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)
Train of Thought: DFS Algorithm
Import java. io. *; import java. util. *; public class Main {public static int map [] [] = new int [5] [5]; public static int fx [] = {0, 0, 1, -1}; public static int fy [] = {1,-1, 0, 0}; public static int px, py; public static void main (String [] args) {consumer SC = new consumer (new BufferedInputStream (System. in); while (SC. hasNextInt () {for (int I = 0; I <map. length; I ++) {for (int j = 0; j <map [I]. length; J ++) {map [I] [j] = SC. nextInt () ;}} map [0] [0] = 3; // mark the pass through px = 0; py = 0; DFS (0, 0 );}} public static void DFS (int p1, int p2) {if (p1 = map. length-1 & p2 = map [0]. length-1) {out (); return;} else {// Four Directions for determination (int I = 0; I <4; I ++) {int px = p1 + fx [I]; int py = p2 + fy [I]; if (check (px, py )) {map [px] [py] = 3; // mark the path through DFS (px, py) ;}}} public static void out () {for (int I = 0; I <5; I ++) {for (int j = 0; j <5; j ++) {if (map [I] [j] = 3) {System. out. println ("(" + I + "," + j + ")") ;}}} public static boolean check (int p1, int p2) {if (p1 <0 | p1> map [0]. length-1 | p2 <0 | p2> map. length-1 | map [p1] [p2]! = 0) return false; elsereturn true ;}}