题目描述
- 地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
- 地址:地址链接
问题分析
- 这是一道升级版的图的遍历题目,不懂为什么《剑指offer》要把它归类为回溯类型的题目,就算是用到了DFS,但也没有像剑指offer-矩阵中的路径一样,利用回溯来清除标记啊。该题中一个坐标遍历完后,便不再遍历。所以,对此,我十分不理解。
- 既然是图的遍历题目,那么有两种方法:
经验教训
- 如何将问题化繁为简,归结为一棵树,或者一个图。这是解dfs或者bfs问题的关键
- 图的遍历的两种方法
- 深刻理解BFS与DFS的区别
代码实现
public int movingCount(int threshold, int rows, int cols) {
if(threshold <= 0) {
return 0;
}
boolean[][] visited = new boolean[rows][cols];
return movingCount(threshold, 0, 0, rows, cols, visited);
}
public int movingCount(int threshold, int i, int j, int rows, int cols, boolean[][] visited) {
if (i < 0 || i >= rows || j < 0 || j >= cols || visited[i][j] || countNum(i) + countNum(j) > threshold){
return 0;
}
visited[i][j] = true;
return 1 + movingCount(threshold, i - 1, j, rows, cols, visited) + movingCount(threshold, i + 1, j, rows, cols, visited) +
movingCount(threshold, i, j - 1, rows, cols, visited) + movingCount(threshold, i, j + 1, rows, cols, visited);
}
public int countNum(int target){
int count = 0;
while(target != 0) {
count += (target % 10);
target = target / 10;
}
return count;
}
public int movingCount(int threshold, int rows, int cols) {
if(threshold <= 0) {
return 0;
}
LinkedList<Point> queue = new LinkedList<>();
boolean[][] visited = new boolean[rows][cols];
visited[0][0] = true;
queue.add(new Point(0,0));
int count = 0;
while (! queue.isEmpty()) {
Point curPoint = queue.poll();
count++;
int x = curPoint.x;
int y = curPoint.y;
if ( isAvailable(x - 1, y, rows, cols, threshold, visited)) {
queue.add(new Point(x - 1, y));
visited[x - 1][y] = true;
}
if (isAvailable(x + 1, y, rows, cols, threshold, visited)) {
queue.add(new Point(x + 1, y));
visited[x + 1][y] = true;
}
if (isAvailable(x, y - 1, rows, cols, threshold, visited)) {
queue.add(new Point(x , y - 1));
visited[x][y - 1] = true;
}
if (isAvailable(x, y + 1, rows, cols, threshold, visited)) {
queue.add(new Point(x, y + 1));
visited[x][y + 1] = true;
}
}
return count;
}
public class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public boolean isAvailable(int x, int y , int rows, int cols, int threshold, boolean[][] visited) {
return (x >= 0 && x < rows && y >= 0 && y < cols && !visited[x][y] && countNum(x) + countNum(y) <= threshold);
}