題目:地上有一個m行和n列的方格。一個機器人從坐标0,0的格子開始移動,每一次隻能向左,右,上,下四個方向移動一格,但是不能進入行坐标和列坐标的數位之和大于k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
思路:(回溯法)可以 前後左右周遊路徑,檢視可否通路。我們可以用 一個數組來記錄通路路徑
class Solution {
public:
int digitsum(int n)
{
int sum =0;
while(n)
{
sum += n%10;
n=n/10;
}return sum;
}
bool checking(int threshold,int rows,int cols,int row,int col,bool* visited)
{
if(rows>row&&row>=0 &&cols>col&&col>=0 &&!visited[row*cols + col]
&& digitsum(col)+digitsum(row)<= threshold)
return true;
return false;
}
int moving(int threshold,int rows,int cols,int row,int col,bool* visited)
{
int count = 0;
if(checking(threshold,rows,cols,row,col,visited))
{
visited[row*cols + col] = true;
count = 1 + moving(threshold,rows,cols,row-1,col,visited)
+ moving(threshold,rows,cols,row+1,col,visited)
+ moving(threshold,rows,cols,row,col-1,visited)
+ moving(threshold,rows,cols,row,col+1,visited);
}return count;
}
int movingCount(int threshold, int rows, int cols)
{
if(threshold<0 || rows<1 || cols<1) return 0;
bool *visited = new bool[rows*cols];
memset(visited,0,rows*cols);
return moving(threshold,rows,cols,0,0,visited);
}
};