华电北风吹
天津大学认知计算与应用重点实验室
日期:2015/10/12
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解析:回溯法(DFS)。每次对可行点四周顺时针寻找下一个可行点,无则回溯。
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;
ReCallFunction(rows, cols, threshold, 0, 0, visited, count);
return count;
}
void ReCallFunction(const int &row, const int &col,const int &limit, int x, int y, bool * visited, int &count)
{
if (x < 0 || x >= col || y < 0 || y >= row)
return;
bool t1 = visited[y*col + x];
bool t2 = Access(x, y, limit);
if ((t1==false) && t2)
{
cout << x << " " << y << endl;
++count;
visited[y*col + x] = true;
ReCallFunction(row, col, limit, x + 1, y, visited, count);
ReCallFunction(row, col, limit, x, y + 1, visited, count);
ReCallFunction(row, col, limit, x - 1, y, visited, count);
ReCallFunction(row, col, limit, x, y - 1, visited, count);
}
}
bool Access(int x, int y,const int & limit)
{
int val = 0;
while (x>0)
{
val += x % 10;
x /= 10;
}
while (y>0)
{
val += y % 10;
y /= 10;
}
return val > limit ? false : true;
}
};