剑指offe-机器人的运动范围

机器人的运动范围

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

解题思路

这道题和剑指offer-矩阵中的路径很相似,递归+回溯。类似的,创建一个一维数组记录某个位置是否被访问过
递归中止条件:矩阵越界,坐标之和不满足条件,当前位置被访问过,返回0

function movingCount(threshold, rows, cols)
{
    let flag = new Array(rows*cols)
    let count = movingCountCore(threshold,rows,cols,0,0,flag)
    return count  
}
function movingCountCore(threshold,rows,cols,i,j,flag){
    if(i<0||j<0||i>=rows||j>=cols||flag[i*cols+j]==true) return 0
    //计算ij之和
    let sum = 0
    let str = `${i}${j}`
    for(let k=0;k<str.length;k++){
        sum +=str.charAt(k)-'0'  //charAt(k)返回str第k位上的字符,-'0'变成数字
    }
    if(sum > threshold){
        return 0
    }
    flag[i*cols+j] = true
    return 1+movingCountCore(threshold,rows,cols,i+1,j,flag)
            +movingCountCore(threshold,rows,cols,i,j+1,flag)
            +movingCountCore(threshold,rows,cols,i-1,j,flag)
            +movingCountCore(threshold,rows,cols,i,j-1,flag)
}

你可能感兴趣的:(剑指offe-机器人的运动范围)