| 1 | class Solution { |
| 2 | public int[][] highestPeak(int[][] isWater) { |
| 3 | // tc: 2*n*m |
| 4 | // sc: n*m |
| 5 | // up, right, down, left |
| 6 | int dir[][] = {{-1,0},{0,1},{1,0},{0,-1}}; |
| 7 | //fill the queue and mark res as negative |
| 8 | int n = isWater.length; |
| 9 | int m = isWater[0].length; |
| 10 | int res[][] = new int[n][m]; |
| 11 | //[r,c] |
| 12 | Queue<int[]> queue = new LinkedList<>(); |
| 13 | for(int i=0;i<n;i++){ |
| 14 | for(int j=0;j<m;j++){ |
| 15 | if(isWater[i][j] == 1){ |
| 16 | res[i][j] = 0; |
| 17 | queue.offer(new int[]{i,j}); |
| 18 | }else{ |
| 19 | res[i][j] = -1; |
| 20 | } |
| 21 | } |
| 22 | } |
| 23 | while(!queue.isEmpty()){ |
| 24 | int cell[] = queue.poll(); |
| 25 | int r = cell[0]; |
| 26 | int c = cell[1]; |
| 27 | int h = res[r][c]; |
| 28 | for(int i=0;i<4;i++){ |
| 29 | int nr = r + dir[i][0]; |
| 30 | int nc = c + dir[i][1]; |
| 31 | if(nr>=0 && nr<n |
| 32 | && nc>=0 && nc<m |
| 33 | && res[nr][nc] == -1){ |
| 34 | res[nr][nc] = h+1; //visit, height++ |
| 35 | queue.offer(new int[]{nr,nc}); |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | return res; |
| 40 | |
| 41 | } |
| 42 | } |