1. 程式人生 > >矩陣dfs--走回路

矩陣dfs--走回路

static [1] array || rpath args 元素 sys lis

矩陣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));
    }
}

  

矩陣dfs--走回路