Java Reference
In-Depth Information
1 1 1 1 1 1 1 1 1 1
1 0 1 0 0 0 1 0 0 1
1 0 1 0 1 0 1 1 0 1
1 0 0 0 1 0 0 0 0 1
1 0 1 1 1 1 1 1 0 1
1 0 1 0 1 0 1 1 0 0
1 0 0 0 0 0 1 1 0 1
1 1 1 1 1 1 1 1 1 1
The start position, S , is at row 6 , column 6 . The first line of data will specify the number of rows and columns of
the maze and the coordinates of S . Thus, the first line of data will be this:
8 10 6 6
This will be followed by the maze data, above.
When we need to mark a position with an x , we will use the value 2 .
Our program will read data from the file maze.in and send output to maze.out . The complete program is shown
as Program P5.3.
Program P5.3
import java.io.*;
import java.util.*;
public class Maze {
static int[][]G; //known to all methods
static int m, n, sr, sc; //known to all methods
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("maze.in"));
PrintWriter out = new PrintWriter(new FileWriter("maze.out"));
getData(in);
if (findPath(sr, sc)) printMaze(out);
else out.printf("\nNo solution\n");
in.close(); out.close();
} // end main
public static void getData(Scanner in) {
m = in.nextInt(); n = in.nextInt();
G = new int[m+1][n+1];
sr = in.nextInt(); sc = in.nextInt();
for (int r = 1; r <= m; r++)
for (int c = 1; c <= n; c++)
G[r][c] = in.nextInt();
} //end getData
public static boolean findPath(int r, int c) {
if (r < 1 || r > m || c < 1 || c > n) return false;
if (G[r][c] == 1) return false; //into a wall
if (G[r][c] == 2) return false; //already considered
// else G[r][c] = 0;
G[r][c] = 2; //mark the path
if (r == 1 || r == m || c == 1 || c == n) return true;
//path found - space located on the border of the maze
Search WWH ::




Custom Search