解题思路
广度优先搜索
代码
class Solution {
public:
int x=0,y=0,now;
int sum = 0;
queue<int> q;
bool vis[10000];
int getDigitSum(int x){
int ans = 0;
while(x){
ans+=x%10;
x/=10;
}
return ans;
}
int movingCount(int m, int n, int k) {
q.push(0);
memset(vis,0,sizeof(vis));
vis[0]=true;
while(!q.empty()){
now = q.front();
++sum;
q.pop();
x = now/n;
y = now%n;
if(x<m-1&&!vis[(x+1)*n+y]&&getDigitSum(x+1)+getDigitSum(y)<=k){
q.push((x+1)*n+y);
vis[(x+1)*n+y] = true;
}
if(y<n-1&&!vis[x*n+y+1]&&getDigitSum(x)+getDigitSum(y+1)<=k){
q.push(x*n+y+1);
vis[x*n+y+1] = true;
}
}
return sum;
}
};