Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9ed0176

Browse files
authored
Merge pull requestneetcode-gh#1477 from elcabalero/patch-4
Update rotting_oranges.cpp as in the video
2 parents7342762 +6eee163 commit9ed0176

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

‎cpp/neetcode_150/11_graphs/rotting_oranges.cpp

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
Time: O(m x n)
88
Space: O(m x n)
99
*/
10-
10+
/*
1111
class Solution {
1212
public:
1313
int orangesRotting(vector<vector<int>>& grid) {
@@ -72,3 +72,48 @@ class Solution {
7272
private:
7373
vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
7474
};
75+
*/
76+
77+
classSolution {
78+
public:
79+
intorangesRotting(vector<vector<int>>& grid) {
80+
int n = grid.size();
81+
int m = grid[0].size();
82+
int time =0;
83+
int fresh =0;
84+
85+
queue<pair<int,int>> q;
86+
87+
vector<pair<int,int>> directions = {{0,1}, {0,-1}, {1,0}, {-1,0}};
88+
89+
for (int i =0; i < n; ++i){
90+
for (int j =0; j < m; ++j){
91+
if (grid[i][j] ==1)
92+
++fresh;
93+
if (grid[i][j] ==2)
94+
q.push({i,j});
95+
}
96+
}
97+
98+
while (!q.empty()and fresh >0){
99+
int size = q.size();
100+
while (size--){
101+
int i = q.front().first;
102+
int j = q.front().second;
103+
q.pop();
104+
for (auto& [x,y] : directions){
105+
int n_i = i + x;
106+
int n_j = j + y;
107+
if (n_i <0 || n_i >= n || n_j <0 || n_j >= m || grid[n_i][n_j] !=1)
108+
continue;
109+
grid[n_i][n_j] =2;
110+
q.push({n_i,n_j});
111+
--fresh;
112+
}
113+
}
114+
++time;
115+
}
116+
117+
return fresh ? -1 : time;
118+
}
119+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp