题解 | #机器人的运动范围#
机器人的运动范围
https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
class Solution {
public:
set<pair<int, int>> hasVisited;
int CalDigitSum(int row, int col) {
int ret = 0;
while (row > 0) {
ret += row % 10;
row /= 10;
}
while (col > 0) {
ret += col % 10;
col /= 10;
}
return ret;
}
void dfs(int threshold, int curRow, int curCol, int edgeRow, int edgeCol, int &sum) {
if (curRow < 0 || curRow >= edgeRow || curCol < 0 || curCol >= edgeCol || hasVisited.count({curRow, curCol})) {
return;
}
if (CalDigitSum(curRow, curCol) > threshold) {
return;
}
hasVisited.insert({curRow, curCol});
sum += 1;
dfs(threshold, curRow + 1, curCol, edgeRow, edgeCol, sum);
dfs(threshold, curRow, curCol + 1, edgeRow, edgeCol, sum);
dfs(threshold, curRow - 1, curCol, edgeRow, edgeCol, sum);
dfs(threshold, curRow, curCol - 1, edgeRow, edgeCol, sum);
}
int movingCount(int threshold, int rows, int cols) {
int sum = 0;
dfs(threshold, 0, 0, rows, cols, sum);
return sum;
}
};
