The solution of this issue is as same as 542. 01 Matrix
class Solution { int m, n; private int[][] dirs ={{-1,0},{1,0},{0,-1},{0,1}}; public void wallsAndGates(int[][] rooms) { if(rooms==null || rooms.length==0) return; m = rooms.length; n = rooms[0].length; Queue<int[]> queue = new LinkedList<>(); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(rooms[i][j]==0){ queue.offer(new int[]{i,j}); } } } int count = 0; while(!queue.isEmpty()){ count++; int size = queue.size(); for(int i=0;i<size;i++){ int[] cell = queue.poll(); for(int[] dir: dirs){ int x = cell[0]+dir[0]; int y = cell[1]+dir[1]; if(x<0||x>=m||y<0||y>=n||rooms[x][y]==-1||rooms[x][y]==0) continue; if(rooms[x][y]==Integer.MAX_VALUE){ queue.offer(new int[]{x,y}); rooms[x][y]=Math.min(rooms[x][y],count); } } } } } }