Created
April 14, 2018 02:04
-
-
Save pwrliang/b5bd34ef58abfd63be494bb38c9ab623 to your computer and use it in GitHub Desktop.
Matrix DFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class MatrixDFS { | |
| int[] moveX = {0, 0, -1, 1}; | |
| int[] moveY = {1, -1, 0, 0}; | |
| boolean[][] visited; | |
| public void search(int[][] matrix, int x, int y, String path) { | |
| path += " -> " + y + "," + x; | |
| if (y == 2 && x == 2) { | |
| System.out.println(path); | |
| System.out.println("--------------"); | |
| } | |
| for (int i = 0; i < 4; i++) { | |
| int nextX = x + moveX[i]; | |
| int nextY = y + moveY[i]; | |
| if (nextX >= 0 && nextX < matrix[0].length && nextY >= 0 && nextY < matrix.length && !visited[nextY][nextX]) { | |
| // we set visited[y][x] instead of visited[nextY][nextX]. Because, if we do so, we will meet the start point again. | |
| // e.g. 0,0(false) 1,0 (true), 2,0 (true), 2,1 (true) 1,1 (true) 0,1 (true) 0,0 (false->true), we revisited the start point | |
| // we had a error result unless we set the start point to be visited before search | |
| visited[y][x] = true; | |
| search(matrix, nextX, nextY,path); | |
| visited[y][x] = false; | |
| } | |
| } | |
| } | |
| public static void main(String[] args) { | |
| MatrixDFS matrixDFS = new MatrixDFS(); | |
| matrixDFS.visited = new boolean[3][3]; | |
| matrixDFS.search(new int[3][3], 0, 0,""); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment