矩阵dfs--走回路

矩阵dfs 走回路 的问题(最后没有在回走---Corner case), 先想好算法, 再自己画图走一遍试试, 递归出口, 注意 corner case, 什么时候符合题意, 什么时候往里面加元素, 边走边看需要 什么工具, 

工具: map(方向), 结果容器, visited, 辅助容器或变量

class Demo {
    List<String> curPath = new ArrayList<>();
    int[][] dirs = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };
    private final Map<Integer, String> dirMap = new HashMap<>();
    String[] dict = new String[]{"up", "right", "down", "left"};
    private int count;

    public List<String> findPath(char[][] maze, int x, int y) {

        int m = maze.length;
        int n = maze[0].length;
        count = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (maze[i][j] == 'T') {
                    count++;
                }
            }
        }

        boolean[][] visited = new boolean[m][n];
        dfs(maze, x, y, visited);

        return count == 0 ? curPath : new ArrayList<>();
    }

    private void dfs(char[][] maze, int x, int y, boolean[][] visited ) {
        if (maze[x][y] != 'T' ) {
            return;
        }
        int m = maze.length;
        int n = maze[0].length;
        visited[x][y] = true;
        count--;

        for (int i = 0; i < 4; i++) {
            int xx = x + dirs[i][0];
            int yy = y + dirs[i][1];

            if (xx < 0 || xx >= m || yy < 0 || yy >= n || visited[xx][yy] || maze[xx][yy] == 'F') {
                continue;
            }
            curPath.add(dict[i]);

            //curPath.add(dirMap.get(i)); // 为啥用map老是 空指针异常啊???
            dfs(maze, xx, yy, visited);
            if (count != 0) {
                curPath.add(dict[(i + 2) % 4]); // 回路
            }

        }


    }
}
public class Robot {


    public static void main(String[] args) {
        Demo r = new Demo();
        char[][] maze = {
                {'T', 'T', 'T', 'F'},
                {'F', 'T', 'F', 'T'},
                {'F', 'T', 'T', 'F'}
        };

        List<String> res = r.findPath(maze, 1, 1);
        System.out.println(String.join(" ", res));
    }
}

  

原文地址:https://www.cnblogs.com/apanda009/p/7278996.html