[The sword refers to the offer brushing the question] 24. The range of motion of the robot

There is a square with m rows and n columns on the ground, and the horizontal and vertical coordinate ranges are 0∼m−1 and 0∼n−1 respectively.

A robot from coordinates (0,0)

The grid starts to move, and each time can only move one grid in four directions: left, right, up, and down.

But can not enter the sum of the digits of row and column coordinates is greater than k

grid.

How many squares can the robot reach?
Example 1

Input: k=7, m=4, n=5

Output: 20

Example 2

Input: k=18, m=40, n=40

Output: 1484

Explanation: When k is 18, the robot is able to enter square (35,37) because 3+5+3+7 = 18.
However, it cannot go into square (35,38) because 3+5+3+8 = 19.

Idea: Breadth-first search

class Solution {
    
    
    private static class Node {
    
    
        int first;
        int second;

        public Node(int first, int second) {
    
    
            this.first = first;
            this.second = second;
        }
    }

    public int movingCount(int threshold, int rows, int cols) {
    
    
        if (rows < 1 || cols < 1)
            return 0;

        boolean[][] visited = new boolean[rows][cols];
        int[][] nxt = {
    
    {
    
    1, 0}, {
    
    -1, 0}, {
    
    0, 1}, {
    
    0, -1}};
        
        Queue<Node> que = new LinkedList<>();
        visited[0][0] = true;
        que.add(new Node(0, 0));
        int res = 0;

        while (!que.isEmpty()) {
    
    
            Node popNode = que.poll();
            res++;

            for (int i = 0; i < nxt.length; i++) {
    
    
                int fx = popNode.first + nxt[i][0], fy = popNode.second + nxt[i][1];
                if (fx >= 0 && fy >= 0 && fx < rows && fy < cols && getSum(fx, fy) <= threshold && !visited[fx][fy]) {
    
    
                    que.add(new Node(fx, fy));
                    visited[fx][fy] = true;
                }
            }
        }

        return res;
    }

    private int getSum(int rows, int cols) {
    
    
        int s = 0;
        while (rows > 0) {
    
    
            s += rows % 10;
            rows /= 10;
        }

        while (cols > 0) {
    
    
            s += cols % 10;
            cols /= 10;
        }

        return s;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326066625&siteId=291194637