LeetCode_Study_Plan/Algorithm

994. Rotting Oranges java

개발하는루루 2022. 12. 30. 00:23

https://leetcode.com/problems/rotting-oranges/description/?envType=study-plan&id=algorithm-i 

 

Rotting Oranges - LeetCode

Rotting Oranges - You are given an m x n grid where each cell can have one of three values: * 0 representing an empty cell, * 1 representing a fresh orange, or * 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacen

leetcode.com

 

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;
    }
}