GuilinDev

Lc0980

05 August 2008

980. Unique Paths III

分析

dfs最基础的应用是寻找迷宫是否能走出 这里多了几个约束条件:

  • 起始位置,终止位置不确定
  • 每一个无障碍方格都要通过一次
  • 求不同路径的数目

分别对上述约束条件进行分析:

  • 先遍历二维数组,找到起始位置,将终止位置作为dfs 的结束标志
  • 设定一个最大步长,并先遍历二维数组,统计最大步长的数值,即0的个数 + 1(当到达终止位置时,grid[i][j] == 2,也算步长 + 1)
  • 加入回溯的思想,在每次对当前位置dfs后(标记grid[y][x] = -1,下次不能走了),将此位置重置回grid[y][x] = 0

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
    int result;
    public int uniquePathsIII(int[][] grid) {
        result = 0;
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return result;
        }
        int m = grid.length;
        int n = grid[0].length;
        int startx = 0, starty = 0;
        int steps = 1;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    startx = i;
                    starty = j;
                    continue;
                }
                if (grid[i][j] == 0) {
                    steps++;
                }
            }
        }
        dfs(grid, startx, starty, steps);
        return result;
    }
    private void dfs(int[][] grid, int px, int py, int steps) {
        if (px < 0 || px >= grid.length || py < 0 || py >= grid[0].length || grid[px][py] == -1) {
            return;
        }
        if (grid[px][py] == 2) {
            if (steps == 0) {
                result++;
            }
            return;
        }
        grid[px][py] = -1;
        steps--;
        dfs(grid, px + 1, py, steps);
        dfs(grid, px - 1, py, steps);
        dfs(grid, px, py + 1, steps);
        dfs(grid, px, py - 1, steps);
        grid[px][py] = 0;
    }
}