题目
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路
还是先定义一个从某点出发的函数,只要满足条件能够到达,则计数+1。与前面题目矩阵中的路径不同的是,此题求的是能够到达的点数,不是存在的路径,故上下左右用加法而不是或。
class Solution { public: int movingCount(int threshold, int rows, int cols) { if(threshold<0||rows<0||cols<0) return 0; vector<vector<bool>> flag(rows,vector<bool>(cols,false)); int sum=movingCountCore(0,0,rows,cols,threshold,flag); return sum; } private: int movingCountCore(int i,int j,int rows,int cols,int threshold,vector<vector<bool>> &flag) { int sum=0; if(check(i,j,rows,cols,threshold,flag)) { flag[i][j]=true; sum=1+movingCountCore(i+1,j,rows,cols,threshold,flag)+ movingCountCore(i-1,j,rows,cols,threshold,flag)+ movingCountCore(i,j+1,rows,cols,threshold,flag)+ movingCountCore(i,j-1,rows,cols,threshold,flag); } return sum; } bool check(int i,int j,int rows,int cols,int threshold,vector<vector<bool>> &flag) { if(i>=0&&i<rows&&j>=0&&j<cols&&getNum(i)+getNum(j)<=threshold&&!flag[i][j]) return true; return false; } int getNum(int n) { int sum=0; while(n) { sum+=n%10; n/=10; } return sum; } };