版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/puliao4167/article/details/85267312
题目描述:地上有一个m行n列的方格,一个机器人从坐标(0,0)的格子开始移动,可以向左右上下四个方向,但是不能进入行坐标和列坐标的数位之和大于k的格子。请问机器人能够达到多少个格子?
解题思路:这道题目也是一道典型的回溯法题目,可以用递归来写。写递归的思路都相似的,通过变化若干个参数调用自己所在的函数。重点在于递归出口的编写。因为本题要求满足条件格子的数量,如果某个格子不满足条件,则返回count=0即可;否则继续遍历四个方向的格子。还需要注意的一点就是要穿是否访问过数组的引用。
class Solution {
public:
int num(int n)
{
int res=0;
while(n!=0)
{
res+=n%10;
n=n/10;
}
return res;
}
int count(int threshold,int rows,int cols,int row,int col,vector<int>& visited)
{
int ct=0;
if(row>=0 && row<rows && col>=0 && col<cols && num(row)+num(col)<=threshold &&
(visited[row*cols+col]==0))//条件满足
{
visited[row*cols+col]=1;
ct=1+count(threshold,rows,cols,row-1,col,visited)+count(threshold,rows,cols,row+1,col,visited)+
count(threshold,rows,cols,row,col-1,visited)+count(threshold,rows,cols,row,col+1,visited);
}
return ct;
}
int movingCount(int threshold, int rows, int cols)
{
if(threshold<=0 && rows<=0 && cols <=0)
{
return 0;
}
int row=0,col=0;
vector<int> visited(rows*cols,0);
int res=count(threshold,rows,cols,row,col,visited);
return res;
}
};