题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
分析:
该题一看就是一题类似于搜索可到达点区域的题目,仅仅是限制了到达条件而已。
所以思路一:DFS深搜,ac代码如下:
class Solution
{
public:
int vis[105][105];//坑爹问题 数组开小了
int a[4]= {-1,1,0,0};
int b[4]= {0,0,-1,1};
int Row,Col;
int judge(int x,int y,int k)
{
int sum=0;
while(x)
{
sum+=x%10;
x/=10;
}
while(y)
{
sum+=y%10;
y/=10;
}
if(sum<=k)
return 1;
return 0;
}
void dfs(int x,int y,int k)
{
vis[x][y]=1;//防止漏掉零点
int tempx,tempy;
for(int i=0; i<4; i++)
{
tempx=x+a[i];
tempy=y+b[i];
if(tempx>=0&&tempx<Row&&tempy>=0&&tempy<Col&&!vis[tempx][tempy]&&judge(tempx,tempy,k))
{
vis[tempx][tempy]=1;
dfs(tempx,tempy,k);
}
}
}
int movingCount(int threshold, int rows, int cols)
{
memset(vis,0,sizeof(vis));
Row=rows;
Col=cols;
int cnt=0;
if(threshold<0)
return 0;
dfs(0,0,threshold);
for(int i=0; i<rows; i++)
for(int j=0; j<cols; j++)
if(vis[i][j])
cnt++;
return cnt;
}
};
很久没有写这种类型的题,一开始数组仅开了50导致怎么都布置错误在哪,低级错误需要注意。同时需要注意k为负值的情况的考虑。常规解法。
思路二:既然如果这个点的横纵坐标满足要求条件的话,那么它通过左边右移或者上边下移到达(在存在多行多列的情况下),因为因为左上两个部分的横纵坐标经过限定条件计算后一定是小于当前点计算后的值的。所以存在多行多列的情况下,直接遍历数组判断符合条件的点数即是所求的点数(需要理解一下)。需要注意在只存在一行一列的时候需要特别考虑,因为只有一行或者一列如果单纯遍历的话,是建立在任何一个点都可以通过下移或者右移得到的,一行一列并不满足此条件,特别处理即可。AC代码如下:
class Solution
{
public:
int vis[105][105];//坑爹问题 数组开小了
int a[4]= {-1,1,0,0};
int b[4]= {0,0,-1,1};
int Row,Col;
int judge(int x,int y,int k)
{
int sum=0;
while(x)
{
sum+=x%10;
x/=10;
}
while(y)
{
sum+=y%10;
y/=10;
}
if(sum<=k)
return 1;
return 0;
}
int movingCount(int threshold, int rows, int cols)
{
int cnt=0;
if(rows==1)
{
for(int i=0; i<cols; i++)
if(judge(0,i,threshold))
cnt++;
else
return cnt;
return cnt;
}
if(cols==1)
{
for(int i=0; i<rows; i++)
if(judge(i,0,threshold))
cnt++;
else
return cnt;
return cnt;
}
for(int i=0; i<rows; i++)
for(int j=0; j<cols; j++)
if(judge(i,j,threshold))
cnt++;
return cnt;
}
};
特记下,以备后日回顾。