The range of motion of the robot java

There is a grid with m rows and n columns on the ground, from coordinate [0,0] to coordinate [m-1, n-1]. A robot starts from the grid of coordinates [0, 0], it can move one grid to the left, right, up, and down at a time (it cannot move outside the grid), nor can it enter the row and column coordinates. The sum of the digits is greater than k's lattice. For example, when k is 18, the robot can enter the square [35, 37] because 3 + 5 + 3 + 7 = 18. But it cannot enter the square [35, 38] because 3 + 5 + 3 + 8 = 19. How many grids can the robot reach?

Deep search : traverse the matrix in a deep search from the starting point, control the deep search boundary and determine whether the number and the position of the current access are less than or equal to k, and need a marker array to record the access of each location to prevent double calculation.

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

    private int dfs(int x, int y, int m, int n, int k, boolean[][] visited) {
        if (x == m || y == n || sum(x) + sum(y) > k || visited[x][y]) {
            return 0;
        }
        visited[x][y] = true;
        return 1 + dfs(x + 1, y, m, n, k, visited) + dfs(x, y + 1, m, n, k, visited);
    }

    // 获取一个整数的数位和
    private int sum(int num) {
        int res = 0;
        while (num > 0) {
            res += num % 10;
            num /= 10;
        }
        return res;
    }
}
Published 23 original articles · praised 1 · visits 464

Guess you like

Origin blog.csdn.net/qq_40492920/article/details/105528201