迷宫问题 回溯
迷宫问题
http://www.nowcoder.com/questionTerminal/cf24906056f4488c9ddb132f317e03bc
package huan._迷宫问题; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { //方向 static int[][] direction = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static int[][] mark; //记录已经访问 static List<int[]> list; //存储结果集 public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()){ list = new ArrayList<>(); int m = in.nextInt(); int n = in.nextInt(); mark = new int[m][n]; int[][] grid = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { grid[i][j] = in.nextInt(); } } dfs(grid, 0, 0); } } public static boolean dfs(int[][] grid, int i, int j) { if (i == grid.length - 1 && j == grid[0].length - 1) { //当到达终点时 输出 list.add(new int[]{i,j}); for (int t = 0; t < list.size(); t++) { System.out.println("("+list.get(t)[0]+","+list.get(t)[1]+")"); } return true; } if (i<0||i>=grid.length||j<0||j>=grid[0].length||mark[i][j]==1) return false; if(grid[i][j]==1)return false; //添加 mark[i][j]=1; list.add(new int[]{i, j}); //做选择 for (int k = 0; k < 4; k++) { int row = i + direction[k][0]; int col = j + direction[k][1]; if (dfs(grid, row, col)){ //如果到达终点 就直接返回 return true; } } //删除 mark[i][j]=0; list.remove(list.size()-1); return false; } }