[剑指offer] 机器人的运动范围
题目
https://www.acwing.com/problem/content/description/22/
思路
方法一
bfs。yxc大佬说如果数据大的时候c++写dfs可能会爆栈。
Java代码
import java.util.LinkedList;
class Solution {
int[] dx = new int[]{-1, 0, 1, 0};
int[] dy = new int[]{0, 1, 0, -1};
public int movingCount(int threshold, int rows, int cols){
if(rows == 0 || cols == 0) return 0;
int res = 0;
boolean[][] st = new boolean[rows][cols];
LinkedList<int[]> q = new LinkedList<>();
q.add(new int[]{0, 0});
while(!q.isEmpty()){
int[] t = q.pop();
if(sum(t[0])+sum(t[1]) > threshold || st[t[0]][t[1]] == true)
continue;
res++;
st[t[0]][t[1]] = true;
for(int i=0; i<4; i++){
int x = rows+dx[i], y = rows+dy[i];
if(t[0] >= 0 && t[0] <rows && t[1] >=0 && t[1] < cols)
q.add(new int[]{t[0], t[1]});
}
}
return res;
}
private static int sum(int x){
int ret = 0;
while(x !=0 ){
ret += x%10;
x /= 10;
}
return ret;
}
}
方法二
bfs。
java代码
class Solution {
int[] dx = new int[]{-1, 0, 1, 0};
int[] dy = new int[]{0, 1, 0, -1};
public int movingCount(int threshold, int rows, int cols){
boolean[][] st = new boolean[rows][cols];
return (dfs(threshold, 0, 0, st, rows, cols));
}
private int dfs(int threshold, int x, int y, boolean[][] st, int rows, int cols){
if(x>=0 && x<rows && y>=0 && y<cols && sum(x)+sum(y)<=threshold && st[x][y]== false){
int ret = 1;
st[x][y] = true;
for(int i=0; i<4; i++){
int a = x+dx[i], b = y+dy[i];
ret += dfs(threshold, a, b, st, rows, cols);
}
return ret;
}
return 0;
}
private static int sum(int x){
int ret = 0;
while(x !=0 ){
ret += x%10;
x /= 10;
}
return ret;
}
}