【剑指Offer】面试题67:机器人的运动范围

来源:互联网 发布:鲍威尔身体数据 编辑:程序博客网 时间:2024/06/05 17:24

一:题目描述

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

二:解题思路

回溯法求解

注意审题,问该机器人能够达到多少个格子,即从上下左右走,能到达格子的总数

对于行坐标和列坐标的数位之和,可以利用 求余后,除以十,直到为0,计算,详见下面函数

判断一个格子是可以到达,需要满足三个条件:

1.在矩阵内

2.行坐标和列坐标的数位之和小于等于阈值

3.格子之前没有被遍历过

三:代码实现

class Solution {public:    int movingCount(int threshold, int rows, int cols)    {        //格子是否到达过        bool* visited=new bool[rows*cols];        memset(visited,false,rows*cols);        int count=0;                count=movingCountCore(threshold,rows,cols,0,0,visited);                delete[] visited;        return count;            }    int movingCountCore(int threshold, int rows, int cols,int row,int col,bool* visited){        //判断格子是否可以进入       //1.在矩阵内  row>=0 && row<rows  && col>=0 && col<cols        //2.行和列的位数之和小于等于阈值  getDigitSum(row)+getDigitSum(col)<=threshold        //3.格子没有被遍历过 visited[row*cols+col]==false                //如果不满足条件,返回0,即不能遍历格子        if(row<0 || row>=rows || col<0 || col>=cols || getDigitSum(row)+getDigitSum(col)>threshold || visited[row*cols+col])            return 0;        //可以遍历,将当前格子置为true        visited[row*cols+col]=true;                //统计其上下左右能遍历的和        int count=0;        count=1+movingCountCore(threshold,rows,cols,row-1,col,visited)            +movingCountCore(threshold,rows,cols,row+1,col,visited)            +movingCountCore(threshold,rows,cols,row,col-1,visited)            +movingCountCore(threshold,rows,cols,row,col+1,visited);                return count;    }    //计算一个数的位数之和    int getDigitSum(int number){        int sum=0;        while(number>0){            sum+=number%10;            number/=10;        }        return sum;    }};

原创粉丝点击