542. 01 Matrix Posted on 2020-07-03 | Edited on 2021-01-22 | Views: 1 LeetCode linkBFSCopy12345678910111213141516171819202122232425262728class Solution { public int[][] updateMatrix(int[][] matrix) { Queue<int[]> queue=new LinkedList<>(); int R=matrix.length,C=matrix[0].length; boolean[][] visited=new boolean[R][C]; for(int i=0;i<R;i++){ for(int j=0;j<C;j++){ if(matrix[i][j]==0){ visited[i][j]=true; queue.offer(new int[]{i,j}); } } } int[][] dirs={{-1,0},{1,0},{0,-1},{0,1}}; while(!queue.isEmpty()){ int[] pos=queue.poll(); for(int[] d:dirs){ int newX=pos[0]+d[0]; int newY=pos[1]+d[1]; if(newX<0||newX>=R||newY<0||newY>=C||visited[newX][newY]) continue; visited[newX][newY]=true; matrix[newX][newY]=matrix[pos[0]][pos[1]]+1; queue.offer(new int[]{newX,newY}); } } return matrix; }}