- LeetCode 최소 하루에 하나는 풀자는 마인드
- 사용언어: JAVA
994. Rotting Oranges
풀이
- 방법: bfs를 활용함. 한 레벨마다 cnt가 올라가므로 cnt를 -1로 초기화함. 오렌지가 rotten된 레벨에서만 cnt++ 할수도 있음.
class Solution {
public int orangesRotting(int[][] grid) {
Queue<int[]> queue = new ArrayDeque<>();
int cnt = -1;
int fresh = 0;
int[][] directions = {
{-1, 0},
{1, 0},
{0, -1},
{0, 1}
};
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == 2) queue.offer(new int[]{i, j});
if(grid[i][j] == 1) fresh++;
}
}
if(fresh == 0) return 0;
while(!queue.isEmpty()){
int level = queue.size();
for(int i = 0; i < level; i++){
int[] orange = queue.poll();
int row = orange[0];
int col = orange[1];
for (int[] dir : directions){
int newRow = row + dir[0];
int newCol = col + dir[1];
if (newRow < 0 || newRow >= grid.length ||
newCol < 0 || newCol >= grid[0].length) {
continue;
}
if (grid[newRow][newCol] != 1) {
continue;
}
grid[newRow][newCol] = 2;
fresh--;
queue.offer(new int[]{newRow, newCol});
}
}
cnt++;
}
if(fresh > 0) cnt = -1;
return cnt;
}
}
- 코드 작성하다가 느낀점
- 앞에서는 dfs만 하다가 갑자기 bfs하니까 적응이 안된다. direction방식은 좋은듯.