-
994. Rotting Oranges javaLeetCode_Study_Plan/Algorithm 2022. 12. 30. 00:23
https://leetcode.com/problems/rotting-oranges/description/?envType=study-plan&id=algorithm-i
class Solution { private final int[][] DIRECTIONS = new int[][]{{-1,0},{0,1},{1,0},{0,-1}}; public int orangesRotting(int[][] grid) { int m = grid.length; int n = grid[0].length; boolean[][] visited = new boolean[m][n]; int[][] ans = new int[m][n]; int max = Integer.MIN_VALUE; Queue<int[]> q = new LinkedList<>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if(grid[i][j]==2){ q.offer(new int[]{i,j}); visited[i][j] = true; } } } while(!q.isEmpty()){ int[] curr = q.poll(); for(int[] d:DIRECTIONS){ int nr = curr[0]+d[0]; int nc = curr[1]+d[1]; if( nr < 0 || nc < 0 || nr >= grid.length || nc >= grid[0].length || grid[nr][nc] != 1 || visited[nr][nc]) continue; ans[nr][nc] = ans[curr[0]][curr[1]]+1; visited[nr][nc] = true; q.offer(new int[]{nr,nc}); } } for (int ii = 0; ii < m; ii++) { for (int jj = 0; jj < n; jj++) { if(grid[ii][jj] == 1 && ans[ii][jj] == 0){ return -1; } max = Math.max(max, ans[ii][jj]); } } System.out.println(Arrays.deepToString(ans)); return max; } }
'LeetCode_Study_Plan > Algorithm' 카테고리의 다른 글
🎵542. 01 Matrix java (0) 2022.12.27 116. Populating Next Right Pointers in Each Node (0) 2022.12.26 🎵 617. Merge Two Binary Trees java (0) 2022.12.26 695. Max Area of Island java (0) 2022.12.22 733. Flood Fill java (0) 2022.12.22