剑指 Offer 13. 机器人的运动范围

136 阅读1分钟

image.png

dfs

class Solution {
    int res = 0;
    boolean[][] visited;
    public int movingCount(int m, int n, int k) {
        visited = new boolean[m][n];
        dfs(m, n, 0, 0, k);
        return res;
    }

    public void dfs(int m, int n, int i, int j, int k) {
        if (i < 0 || j < 0 || i > m - 1 || j > n - 1 
            || !isValid(i, j, k)
            || visited[i][j]) {
            return;
        }
        res++;
        visited[i][j] = true;
        dfs(m, n, i - 1, j, k);
        dfs(m, n, i + 1, j, k);
        dfs(m, n, i, j - 1, k);
        dfs(m, n, i, j + 1, k);
    }

    public boolean isValid(int m, int n, int k) {
        int num = 0;
        while (m > 0) {
            num += m % 10;
            m /= 10;
        }
        while (n > 0) {
            num += n % 10;
            n /= 10;
        }
        return num <= k;
    }
}

bfs

class Solution {
    public int movingCount(int m, int n, int k) {
        int res = 0;
        boolean[][] visited = new boolean[m][n];
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);
        visited[0][0] = true;
        res++; // +1先
        while (!queue.isEmpty()) {
            int tmp = queue.poll();
            in\t curI = tmp / n;
            int curJ = tmp % n;
            if (curI + 1 < m && isValid(curI + 1, curJ, k) && !visited[curI + 1][curJ]) {
                queue.offer((curI + 1) * n + curJ);
                visited[curI + 1][curJ] = true;
                res++;
            }
            if (curJ + 1 < n && isValid(curI, curJ + 1, k) && !visited[curI][curJ + 1]) {
                queue.offer(curI * n + curJ + 1);
                visited[curI][curJ + 1] = true;
                res++;
            }
            if (curI - 1 >= 0 && isValid(curI - 1, curJ, k) && !visited[curI - 1][curJ]) {
                queue.offer((curI - 1) * n + curJ);
                visited[curI - 1][curJ] = true;
                res++;
            }
            if (curJ - 1 >= 0 && isValid(curI, curJ - 1, k) && !visited[curI][curJ - 1]) {
                queue.offer(curI * n + curJ - 1);
                visited[curI][curJ - 1] = true;
                res++;
            }
        }
        return res;
    }

    public boolean isValid(int m, int n, int k) {
        int sum = 0;
        while (m > 0) {
            sum += m % 10;
            m /= 10;
        }
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum <= k;
    }
}