一开始想错了,机器人只能从一个点进入,不可以随机挑选点进入
class Solution {
public:
int movingCount(int threshold, int rows, int cols) {
int res = 0;
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix[i][j] = i % 10 + i / 10 + j % 10 + j / 10;
}
}
// 只能从一个起点开始探索
dfs(matrix, threshold, rows, cols, 0, 0, res);
return res;
}
private:
void dfs(std::vector<std::vector<int>> &matrix, const int &threshold, const int &rows, const int &cols, int i, int j, int &res) {
if (i >= rows || i < 0 || j >= cols || j < 0 || matrix[i][j] == -1 || matrix[i][j] > threshold) {
return ;
}
++res;
matrix[i][j] = -1;
dfs(matrix, threshold, rows, cols, i + 1, j, res);
dfs(matrix, threshold, rows, cols, i - 1, j, res);
dfs(matrix, threshold, rows, cols, i, j + 1, res);
dfs(matrix, threshold, rows, cols, i, j - 1, res);
}
};