-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.cpp
44 lines (40 loc) · 1.17 KB
/
solution.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution
{
public:
vector<vector<int>> highestPeak(vector<vector<int>> &isWater)
{
int m = isWater.size(), n = isWater[0].size();
vector<vector<int>> height(m, vector<int>(n, -1));
queue<pair<int, int>> q;
// Initialize the queue with all water cells
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (isWater[i][j] == 1)
{
height[i][j] = 0;
q.push({i, j});
}
}
}
// Directions for BFS (up, down, left, right)
vector<pair<int, int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
// BFS
while (!q.empty())
{
auto [x, y] = q.front();
q.pop();
for (auto [dx, dy] : directions)
{
int nx = x + dx, ny = y + dy;
if (nx >= 0 && ny >= 0 && nx < m && ny < n && height[nx][ny] == -1)
{
height[nx][ny] = height[x][y] + 1;
q.push({nx, ny});
}
}
}
return height;
}
};