BFS
BFS 总共有两个模板:
1.如果不需要确定当前遍历到了哪一层,BFS 模板如下。
while(!queue.isEmpty()){
cur = queue.poll()
for 节点 in cur的所有相邻节点:
if 该节点有效且未访问过:
queue.push(该节点)
}
例题:LeeCode522
class Solution {
public int[][] updateMatrix(int[][] mat) {
int[][] dirs={
{
1,0},{
-1,0},{
0,1},{
0,-1}};
int m = mat.length;
int n = mat[0].length;
int[][] res = new int[m][n];
boolean[][] visited = new boolean[m][n];
Queue<int[]> queue = new LinkedList<>();
for(int i=0;i<m;i