Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Tcdian opened this issue Apr 8, 2020 · 1 comment
Open

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

Tcdian opened this issue Apr 8, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 8, 2020

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

地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?

Example 1

输入:m = 2, n = 3, k = 1
输出:3

Example 2

输入:m = 3, n = 1, k = 0
输出:1

Note

  • 1 <= n,m <= 100
  • 0 <= k <= 20
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 8, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} m
 * @param {number} n
 * @param {number} k
 * @return {number}
 */
var movingCount = function(m, n, k) {
    const queue = [[0, 0]];
    const direction = [0, 1, 0];
    const visited = new Set();
    let result = 0;
    while(queue.length !== 0) {
        const p = queue.shift();
        result += 1;
        for (let i = 0; i < 2; i++) {
            const positionX = p[0] + direction[i];
            const positionY = p[1] + direction[i + 1];
            if (positionX >= 0 && positionX < m && positionY >= 0 && positionY < n) {
                const digitSum = positionX % 10 + Math.floor(positionX / 10)
                    + positionY % 10 + Math.floor(positionY / 10);
                if (digitSum <= k && !visited.has(positionX * 100 + positionY)) {
                    queue.push([positionX, positionY]);
                    visited.add(positionX * 100 + positionY);
                }
            }
        }
    }
    return result
};

@Tcdian Tcdian changed the title 《剑指 Offer(第 2 版)》13. 机器人的运动范围 剑指 Offer 13. 机器人的运动范围 Jun 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant