https://leetcode.com/problems/rotting-oranges/description/
class Solution {
public int orangesRotting(int[][] grid) {
Queue<int[]> queue = new LinkedList<>();
int total = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 2) {
total += 1;
queue.add(new int[]{i, j});
}
if (grid[i][j] == 1) {
total += 1;
}
}
}
int rotten = 0, minute = 0;
while(true) {
Queue<int[]> temp = new LinkedList<>(queue);
rotten = 0;
while(!temp.isEmpty()) {
int[] curr = temp.poll();
if (curr[0] - 1 >= 0 && grid[curr[0] - 1][curr[1]] == 1) {
rotten += 1;
grid[curr[0] - 1][curr[1]] = 2;
queue.add(new int[]{curr[0] - 1, curr[1]});
}
if (curr[1] - 1 >= 0 && grid[curr[0]][curr[1] - 1] == 1) {
rotten += 1;
grid[curr[0]][curr[1] - 1] = 2;
queue.add(new int[]{curr[0], curr[1] - 1});
}
if (curr[0] + 1 < grid.length && grid[curr[0] + 1][curr[1]] == 1) {
rotten += 1;
grid[curr[0] + 1][curr[1]] = 2;
queue.add(new int[]{curr[0] + 1, curr[1]});
}
if (curr[1] + 1 < grid[0].length && grid[curr[0]][curr[1] + 1] == 1) {
rotten += 1;
grid[curr[0]][curr[1] + 1] = 2;
queue.add(new int[]{curr[0], curr[1] + 1});
}
}
if (rotten == 0) {
break;
}
minute++;
}
if (queue.size() == total) {
return minute;
}
return -1;
}
}
'코딩테스트' 카테고리의 다른 글
[programmers] 이모티콘 할인행사 (0) | 2024.03.13 |
---|---|
33. Search in Rotated Sorted Array (0) | 2024.02.22 |
75. Sort Colors (0) | 2024.02.18 |
268. Missing Number (0) | 2024.02.17 |
283. Move Zeroes (0) | 2024.02.17 |