和NO65差不多,dfs即可。
#include <vector>
using namespace std;
class Solution {
public:
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
int row;
int col;
int count;
int t;
int movingCount(int threshold, int rows, int cols) {
if(rows <=0 || cols <=0) return 0;
row = rows;
col = cols;
t = threshold;
count = 0;
vector<vector<bool>> visited(row, vector<bool>(col, false));
dfs(0, 0, visited);
return count;
}
void dfs(int i, int j, vector<vector<bool>>& v){
// 检查坐标合法性、是否已访问及数位和条件
if(i < 0 || i >= row || j < 0 || j >= col || v[i][j] || cal(i, j) > t)
return;
v[i][j] = true; // 标记当前格子为已访问
count++; // 增加可达格子数
// 向四个方向继续搜索
for(int l = 0; l < 4; l++){
int curx = dx[l] + i;
int cury = dy[l] + j;
dfs(curx, cury, v);
}
}
int cal(int x, int y){
int res = 0;
while(x != 0){
res += x % 10;
x /= 10;
}
while(y != 0){
res += y % 10;
y /= 10;
}
return res;
}
};