- 算法
- 1.广度优先搜素
- 2.队列实现广度优先搜索,visited数组记录已访问坐标
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) { int[][] result = new int[R*C][2]; int i = 0; boolean[][] visited = new boolean[R][C]; visited[r0][c0] = true; Queue<int[]> queue = new LinkedList<>(); queue.offer(new int[]{r0, c0}); while (!queue.isEmpty()) { int size = queue.size(); while (size-- > 0) { int[] curr = queue.poll(); result[i++] = curr; if (curr[0] - 1 >= 0 && !visited[curr[0]-1][curr[1]]) { queue.offer(new int[]{curr[0]-1, curr[1]}); visited[curr[0]-1][curr[1]] = true; } if (curr[0] + 1 < R && !visited[curr[0]+1][curr[1]]) { queue.offer(new int[]{curr[0]+1, curr[1]}); visited[curr[0]+1][curr[1]] = true; } if (curr[1] - 1 >= 0 && !visited[curr[0]][curr[1]-1]) { queue.offer(new int[]{curr[0], curr[1]-1}); visited[curr[0]][curr[1]-1] = true; } if (curr[1] + 1 < C && !visited[curr[0]][curr[1]+1]) { queue.offer(new int[]{curr[0], curr[1]+1}); visited[curr[0]][curr[1]+1] = true; } } } return result; }
func allCellsDistOrder(R int, C int, r0 int, c0 int) [][]int { result := make([][]int, R * C) i := 0 visited := make([][]bool, R) for i := range visited { visited[i] = make([]bool, C) } visited[r0][c0] = true l := list.New() l.PushBack([]int{r0, c0}) for l.Len() > 0 { size := l.Len() for size > 0 { curr := l.Remove(l.Front()) p := curr.([]int) result[i] = p i++ if p[0] - 1 >= 0 && !visited[p[0] - 1][p[1]] { l.PushBack([]int{p[0] - 1, p[1]}) visited[p[0] - 1][p[1]] = true } if p[0] + 1 < R && !visited[p[0] + 1][p[1]] { l.PushBack([]int{p[0] + 1, p[1]}) visited[p[0] + 1][p[1]] = true } if p[1] - 1 >= 0 && !visited[p[0]][p[1] - 1] { l.PushBack([]int{p[0], p[1] - 1}) visited[p[0]][p[1] - 1] = true } if p[1] + 1 < C && !visited[p[0]][p[1] + 1] { l.PushBack([]int{p[0], p[1] + 1}) visited[p[0]][p[1] + 1] = true } size-- } } return result }