LeetCode T Interview Question 13. The range of motion of the robot

description

There is a grid with m rows and n columns on the ground, from coordinates  [0,0] to coordinates  [m-1,n-1] . A robot [0, 0] starts to move from a grid of coordinates  . It can move one grid to the left, right, up, and down at a time (it cannot move beyond the grid), nor can it enter a grid where the sum of the row and column coordinates is greater than k. 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?

Example 1

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

Example 2

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

prompt:

• 1 <= n,m <= 1000 <= k <= 20

analysis

Obviously, the main idea for solving the problem is  广度优先搜索 or  深度优先搜索 , where you can get through a picture example,

m=20n=15k=9 Situation

We see that although there are green squares in the lower right corner, we cannot go to these positions, so the final position that can be passed should be

Code

/** * @param {number} m * @param {number} n * @param {number} k * @return {number} */var movingCount = function(m, n, k) {    let step = {}
    let num = 0    function dfs(i,j){        if(i<0 || j<0 || i>=m || j>=n) return
        if(!step[`${i}|${j}`] && canMove(i,j,k)){            step[`${i}|${j}`] = true            num++
            dfs(i-1,j)            dfs(i+1,j)            dfs(i,j-1)            dfs(i,j+1)        }    }    dfs(0,0)    return num};function canMove(i,j,k){    let vali = i.toString().split('').reduce((a,b)=>{return Number(a) + Number(b)})    let valj = j.toString().split('').reduce((a,b)=>{return Number(a) + Number(b)})    if((Number(vali) + Number(valj)) <= k) return true    return false}

 

Published 117 original articles · 69 praises · 10,000+ views

Guess you like

Origin blog.csdn.net/zsd0819qwq/article/details/105402201