반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- array
- JSX
- queue
- map
- node.js
- leetcode
- Props
- Context
- css
- c++
- 비트연산
- event
- DP
- count
- Callback
- React
- UE5
- axios
- state
- priority_queue
- treenode
- component
- routes
- bit
- route
- BinaryTree
- Navigation
- nodeJS
- MySQL
- server
Archives
- Today
- Total
우사미 코딩
[Leetcode] 994. Rotting Oranges - BFS 본문
반응형
1. 문제링크
Rotting Oranges - LeetCode
Can you solve this real interview question? 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
leetcode.com
2. key point - queue를 사용하자
1) 상한 오렌지 q에 넣기
2) 오렌지는 자기 주변 4셀(상하좌우)만 썩게 할 수 있음
3) 상태가 1에서 2로 변경되는 오렌지는 q에 넣어주기
4) q가 empty가 될 때 까지 반복한다
3. solution
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
int days = 0;
int m = grid.size(), n = grid[0].size();
queue<pair<int, int>> q;
vector<pair<int, int >> dir = {{-1,0}, {0, -1}, {1, 0}, {0, 1}};
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == 2){
q.push({i, j});
}
}
}
while(!q.empty()){
int size = q.size();
bool rotted = false;
while(size-- > 0){
pair<int, int> node = q.front();
q.pop();
for(int t = 0; t < dir.size(); t++){
int row = node.first + dir[t].first;
int col = node.second + dir[t].second;
if((row >= 0 && row < m && col >= 0 && col < n) && grid[row][col] == 1){
grid[row][col] = 2;
q.push({row, col});
rotted = true;
}
}
}
if(rotted)
days++;
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(grid[i][j] == 1){
return -1;
}
}
}
return days;
}
};
반응형
'Leetcode' 카테고리의 다른 글
[Leetcode] 322. Coin Change - DP (0) | 2023.05.28 |
---|---|
[Leetcode] 210. Course Schedule II - Topological Sorting (0) | 2023.05.27 |
[Leetcode] 621. Task Scheduler (0) | 2023.05.26 |
[Leetcode] 33. Search in Rotated Sorted Array - binary search (0) | 2023.05.23 |
[Leetcode] 437. Path Sum III (0) | 2023.05.23 |
Comments