13.机器人的运动范围
题目和代码来自书上
以下是牛客网上ac过的代码
class Solution {
public:
int movingCount(int threshold, int rows, int cols)
{
if (threshold < 0 || rows <= 0 || cols <= 0) return 0;
vector<vector<bool>> visited;
for (int i = 0; i < rows; i++ ) {
vector<bool> tmp_rows(cols,false);
visited.push_back(tmp_rows);
}
int ret = movingCountCore(threshold, rows, cols,0,0, visited);
return ret;
}
int movingCountCore(int threshold, int rows, int cols, int i, int j, vector<vector<bool>>& visited ) {
int count = 0;
if (check(threshold, i,j, rows, cols,visited)) {
visited[i][j] = true;
count = 1 + movingCountCore(threshold, rows, cols, i+1, j, visited)
+ movingCountCore(threshold, rows, cols, i-1, j, visited)
+ movingCountCore(threshold, rows, cols, i, j+1, visited)
+ movingCountCore(threshold, rows, cols, i, j-1, visited);
}
return count;
}
int check(int threshold, int i, int j, int rows, int cols, vector<vector<bool>>& visited) {
if (i >= 0 && i < rows
&& j >= 0 && j < cols
&& !visited[i][j]
&& get_num(i) + get_num(j) <= threshold) {
return true;
}
return false;
}
int get_num(int num) {
int sum = 0;
while(num>0) {
sum += num % 10;
num /= 10;
}
return sum;
}
};
最近比较忙,练的题目比较少,要加油啊!!