剑指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。请问该机器人能够到达多少个格子?

示例 1:

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

示例 2:

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

提示:

1 <= n,m <= 100
0 <= k <= 20

解题:

  • 本题使用的方法同样还是回溯法,另外还需要会计算给定整数上的各个位上数之和。
  • 使用一个访问数组记录是否已经经过该格子。
  • 机器人从(0,0)开始移动,当它准备进入(i,j)的格子时,通过检查坐标的数位来判断机器人是否能够进入。
  • 如果机器人能进入(i,j)的格子,接着在判断它是否能进入四个相邻的格子(i,j-1),(i,j+1),(i-1,j),(i+1,j)。
  • 因此,可以用回溯法来解决这一问题。
public class Solution {
    //回溯法
    public int movingCount(int threshold, int rows, int cols) {
        if(rows<=0||cols<=0||threshold<0)   return 0;
        int[] visited=new int[rows*cols];
        return MovingCount(threshold,rows,cols,0,0,visited);
    }
 
    private int MovingCount(int threshold,int rows,int cols,int row,int col,int[] visited){
        int count=0;
        if(canWalkInto(threshold, rows, cols, row, col, visited)){
            visited[row*cols+col]=1;
            count=1+MovingCount(threshold,rows,cols,row-1,col,visited)   //往上
                    +MovingCount(threshold,rows,cols,row+1,col,visited)  //往下
                    +MovingCount(threshold, rows, cols, row, col-1, visited)   //往左
                    +MovingCount(threshold, rows, cols, row, col+1, visited);  //往右
        }
        return count;
    }
 
    private boolean canWalkInto(int threshold,int rows,int cols,int row,int col,int[] visited){
        if(row>=0 && row<rows && col>=0 && col<cols
                && getSumOfDigits(row)+getSumOfDigits(col)<=threshold
                && visited[row*cols+col]==0)
            return true;
        else
            return false;
    }
 
    private int getSumOfDigits(int number){
        int sum=0;
        while(number!=0){
            sum+=number%10;
            number/=10;
        }
        return sum;
    }
}
发布了106 篇原创文章 · 获赞 113 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/qq_41598072/article/details/104400685
今日推荐