DFS
【思路】
遍历每一个合法位置
class Solution {
int ans = 0;
int [][] dir = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, - 1}};
public int get_single_sum(int x){
int res = 0;
while(x > 0){
res = res + x % 10;
x /= 10;
}
return res;
}
public int get_sum(int x, int y){
return get_single_sum(x) + get_single_sum(y);
}
public void dfs(int k, int x, int y, boolean st[][]){
if( get_sum(x, y) > k ) return;
int m = st.length, n = st[0].length;
st[x][y] = true;
ans ++;
for(int i = 0; i < 4; i ++){
int nx = x +dir[i][0], ny = y + dir[i][1];
if(nx >= 0 && nx < m && ny >=0 && ny < n && !st[nx][ny])
dfs(k, nx, ny, st);
}
}
public int movingCount(int threshold, int rows, int cols)
{
if(rows == 0 || cols == 0) return 0;
boolean st[][] = new boolean[rows][cols];
dfs(threshold, 0, 0, st);
return ans;
}
}
BFS
【思路】
BFS 统计队列中合法的且没有被访问过的点的且符合题意的个数
class node{
int x, y;
public node(int xx, int yy){
x = xx;
y = yy;
}
}
class Solution {
public int get_single_sum(int t){// 123
int res = 0;
while(t > 0){
res = res + t % 10;
t /= 10;
}
return res;
}
public int get_sum(int x, int y){
return get_single_sum(x) + get_single_sum(y);
}
public int movingCount(int threshold, int rows, int cols)
{
//特判边界
if( rows == 0 || cols == 0) return 0;
int ans = 0;
LinkedList<node> q = new LinkedList<node>();
boolean st[][] = new boolean[rows][cols];
int dir[][] = {{-1, 0}, {0, 1}, {1, 0}, {0,-1}};
//合法则放进队列
q.push(new node(0, 0));
st[0][0] = true;
ans ++;
while(! q.isEmpty()){
node head = q.peek();
q.pop();
for(int i = 0; i < 4; i ++){
int nx = head.x +dir[i][0], ny = head.y +dir[i][1];
//每次扩展合法、没有遍历过的且符合题意
//(即该格子行坐标和列坐标的数位之和不大于 k)点到队列中
if( nx >= 0 && nx < rows && ny >= 0 && ny < cols && !st[nx][ny]
&& get_sum(nx,ny) <= threshold ){
st[nx][ny] = true;
q.push(new node(nx, ny));
ans ++;
}
}
}
return ans;
}
}