题目描述
具体代码
class Solution {
// 每个方格的状态表
public int[][] table;
// 总行数
public int rows;
// 总列数
public int cols;
public int movingCount(int threshold, int rows, int cols) {
// 初始化基本数据
table = new int[rows][cols];
this.rows = rows;
this.cols = cols;
// 找出机器人不能够走的方格,并将状态标为-1
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
String string = String.valueOf(i) + String.valueOf(j);
int sum = 0;
for(char c : string.toCharArray()) {
sum += Integer.valueOf(String.valueOf(c));
if(sum > threshold) {
table[i][j] = -1;
}
}
}
}
// 深度搜索
dfs(0, 0);
int count = 0;
// 找出所有标记为1的方格,即为答案
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(table[i][j] == 1) {
count++;
}
}
}
return count;
}
public void dfs(int x, int y) {
// 遍历到超出范围、状态为1或-1的方格时停止此次的dfs
if(x < 0 || y < 0 || x > cols-1 || y > rows-1 || table[y][x] != 0) {
return;
}
// 将当前的方格标记为1
table[y][x] = 1;
// 分别对应机器人上、下、左、右移动的情况
dfs(x, y-1);
dfs(x, y+1);
dfs(x-1, y);
dfs(x+1, y);
}
}
运行结果
18
40
40
1484
文章转载自云丶言,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。





