lc interview question 13. The range of motion of the robot
There is a grid with m rows and n columns on the ground, from coordinate [0,0] to coordinate [m-1, n-1]. A robot starts from
the grid of coordinates [0, 0] , it can move one grid to the left, right, up, and down at a time (it cannot move outside the grid), nor can it enter the row and column coordinates. k's lattice. For example, when k is 18, the robot can enter the square
[35, 37] because 3 + 5 + 3 + 7 = 18. But it cannot enter the square [35, 38] because 3 + 5 + 3 + 8 = 19. How many grids can the robot reach?Source: LeetCode
Link: https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
Copyright belongs to the deduction network. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.
Solution method: BFS. BFS is traversal, but uses the breadth-first approach. This problem can also be solved with depth priority. This question is similar to the process of manually solving the problem: starting from [0,0], you can save it, and you ca n’t skip it.
class Solution {
public int movingCount(int m, int n, int k) {
boolean[][] visited = new boolean[m][n];
int res = 0;
Queue<int[]> queue= new LinkedList<int[]>();
queue.add(new int[] { 0, 0, 0, 0 });
while(queue.size() > 0) {
int[] x = queue.poll();
int i = x[0], j = x[1], si = x[2], sj = x[3];
if(i < 0 || i >= m || j < 0 || j >= n || k < si + sj || visited[i][j]) continue;//不可以走,跳过,不进行遍历。
visited[i][j] = true;
res ++;
queue.add(new int[] { i + 1, j, (i + 1) % 10 != 0 ? si + 1 : si - 8, sj });//右边一个位置
queue.add(new int[] { i, j + 1, si, (j + 1) % 10 != 0 ? sj + 1 : sj - 8 });//下边一个位置
}
return res;
}
}