public class Maze { private final int tried = 3; private final int path = 7; private int[][] grid = { {1,1,1,0,1,1,0,0,0,1,1,1,1}, {1,0,1,1,1,0,1,1,1,1,0,0,1}, {0,0,0,0,1,0,1,0,1,0,1,0,0}, {1,1,1,0,1,1,1,0,1,0,1,1,1}, {1,0,1,0,0,0,0,1,1,1,0,0,1}, {1,0,1,1,1,1,1,1,0,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,1,1,1,1,1,1,1,1,1,1,1} }; public boolean traverse(int row, int col) { boolean done = false; if (valid(row, col)) { grid[row][col] = tried; // we've visited this cell if (row == grid.length - 1 && col == grid[0].length -1) { // we're in the lower right - done! done = true; } else { done = traverse(row+1, col); //try to move down if (!done) done = traverse(row, col+1); // try to move right if (!done) done = traverse(row-1, col); // try to move left if (!done) done = traverse(row, col-1); // try to move up } if (done) // this cell is part if the solution grid[row][col] = path; } return done; } public boolean valid(int row, int col) { boolean result = false; // are we inside the matrix? if (row >= 0 && row < grid.length && col >= 0 && col < grid[row].length) { // Is the cell either blocked or previously tried? if (grid[row][col] == 1) { result = true; } } return result; } public String toString() { String result = "\n"; for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[row].length; col++) { result += grid[row][col] + " "; } result += "\n"; } return result; } }