题解 | #机器人的运动范围#
机器人的运动范围
http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
public:
int movingCount(int threshold, int rows, int cols) {
if (rows <= 0 || cols <= 0 || threshold < 0)
return 0;
vector<vector<int>>matrix(rows, vector<int>(cols, 0));
return dfs(matrix, threshold, rows, cols, 0, 0);
}
int dfs(vector<vector<int>>&matrix, int threshold, int rows, int cols, int x,
int y) {
if (!(valid(threshold, x, y, rows, cols))) return 0;
if (matrix[x][y] != 0) return 0;
matrix[x][y] = 1;
return 1 + dfs(matrix, threshold, rows, cols, x + 1, y) +
dfs(matrix, threshold, rows, cols, x - 1, y) +
dfs(matrix, threshold, rows, cols, x, y + 1) +
dfs(matrix, threshold, rows, cols, x, y - 1);
}
bool valid(int threshold, int x, int y, int rows, int cols) {
if (x < 0 || x >= rows || y < 0 || y >= cols) {
return false;
}
if (cal(x)+cal(y) > threshold) {
return false;
}
return true;
}
int cal(int num){
int sum=0;
while(num){
sum+=num%10;
num=num/10;
}
return sum;
}
};