此题可用广度优先搜索(BFS)来解决
需要注意的是threshold有可能为负数
struct point
{
int x;
int y;
point(int a, int b) :x(a), y(b){};
};
class Solution {
public:
bool valid(int row, int col, int threshold)
{
int num = 0;
while (row != 0)
{
num += row % 10;
row /= 10;
}
while (col != 0)
{
num += col % 10;
col /= 10;
}
return num <= threshold ? true : false;
}
int movingCount(int threshold, int rows, int cols)
{
queue<point > q;
point temp(0, 0);
q.push(temp);
vector<vector<bool >> visited(rows, vector<bool>(cols, false));
visited[0][0] = true;
int result = 0;
if (!valid(0, 0, threshold))
return result;
while (!q.empty())
{
point p = q.front();
q.pop();
int row = p.x;
int col = p.y;
cout << row << " " << col << endl;
result++;
//查找周围其他元素
if (row - 1 >= 0 && visited[row - 1][col] == false && valid(row - 1, col, threshold))
{
point temp(row - 1, col);
visited[row-1][col] = true;
q.push(temp);
}
if (row + 1<rows&&visited[row + 1][col] == false && valid(row + 1, col, threshold))
{
point temp(row + 1, col);
visited[row+1][col] = true;
q.push(temp);
}
if (col - 1 >= 0 && visited[row][col - 1] == false && valid(row, col - 1, threshold))
{
point tenp(row, col - 1);
visited[row][col-1] = true;
q.push(temp);
}
if (col + 1<cols&&visited[row][col + 1] == false && valid(row, col + 1, threshold))
{
point temp(row, col + 1);
visited[row][col+1] = true;
q.push(temp);
}
}
return result;
}
};