BFS相关题总结
填充每个节点的下一个右侧节点指针
层次遍历
将二叉树的每一层节点都连接起来形成链表。
层次遍历基于广度优先搜索 区别在于:广度优先搜索每次只会取出一个节点来拓展,而层次遍历每次将队列中的所有元素拿来拓展,
保证每次从队列中拿出来遍历的元素都是同一层的。
class Solution {
public Node connect(Node root) {
if (root == null) return null;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Node tmp = queue.poll();
if (i < size - 1) {
tmp.next = queue.peek();
}
if (tmp.left != null) {
queue.add(tmp.left);
}
if (tmp.right != null) {
queue.add(tmp.right);
}
}
}
return root;
}
}
递归:
class Solution {
public Node connect(Node root) {
dfs(root);
return root;
}
public void dfs(Node root) {
if (root == null) return;
Node left = root.left;
Node right = root.right;
while (left != null) {
left.next = right;
left = left.right;
right = right.left;
}
dfs(root.left);
dfs(root.right);
}
}
笔记:
Queue 中 poll()和 remove()有什么区别
PriorityQueue(优先队列)的用法
01矩阵
class Solution {
public int[][] updateMatrix(int[][] mat) {
Queue<int[]>queue=new LinkedList<>();
int m= mat.length;
int n=mat[0].length;
for (int i = 0; i < m; i++) {
for(int j=0;j<n;j++){
if(mat[i][j]==0){
queue.offer(new int[]{i,j});
}
else{
mat[i][j]=-1;
}
}
}
int []dx=new int[]{0,1,-1,0};
int []dy=new int[]{1,0,0,-1};
while(!queue.isEmpty()){
int []point=queue.poll();
int x=point[0];
int y=point[1];
for(int i=0;i<4;i++){
int nex_x=x+dx[i];
int nex_y=y+dy[i];
if(nex_x>=0&&nex_x<m&&nex_y>=0&&nex_y<n&&mat[nex_x][nex_y]==-1){
mat[nex_x][nex_y]=mat[x][y]+1;
queue.offer(new int[]{nex_x,nex_y});
}
}
}
return mat;
}
}
腐烂的橘子
class Solution {
public int orangesRotting(int[][] grid) {
int[] dx = new int[]{-1, 0, 0, 1};
int[] dy = new int[]{0, 1, -1, 0};
int m = grid.length;
int n = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
ans++;
} else if (grid[i][j] == 2) {
queue.add(new int[]{i, j});
}
}
}
int round = 0;
while (ans > 0 && !queue.isEmpty()) {
int size = queue.size();
round++;
for (int i = 0; i < size; i++) {
int[] orange = queue.poll();
int x = orange[0];
int y = orange[1];
for (int j = 0; j < 4; j++) {
int new_x = x + dx[j];
int new_y = y + dy[j];
if (new_x >= 0 & new_x < m & new_y >= 0 && new_y < n && grid[new_x][new_y] == 1) {
grid[new_x][new_y] = 2;
ans--;
queue.add(new int[]{new_x, new_y});
}
}
}
}
if (ans > 0) return -1;
else {
return round;
}
}
}