- Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode1162-as-far-from-land-as-possible_bfs2.cpp
70 lines (66 loc) · 1.69 KB
/
leetcode1162-as-far-from-land-as-possible_bfs2.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<vector>
#include<queue>
#include<algorithm>
#include<iostream>
usingnamespacestd;
classSolution {
constint dx[4] = {0, 1, 0, -1};
constint dy[4] = {1, 0, -1, 0};
public:
intmaxDistance(vector<vector<int>>& grid) {
constint N = grid.size();
deque<pair<int, int>> q;
int d[N][N];
for (auto& row : d)
fill(row, row + N, 1000);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
if (grid[i][j] == 1)
{
q.push_back(make_pair(i, j));
d[i][j] = 0;
}
}
while (!q.empty())
{
auto kvp = q.front();
q.pop_front();
for (int i = 0; i < 4; i++)
{
int newX = kvp.first + dx[i], newY = kvp.second + dy[i];
if (newX < 0 || newX >= N || newY < 0 || newY >= N)
continue;
if (d[newX][newY] > d[kvp.first][kvp.second] + 1)
{
d[newX][newY] = d[kvp.first][kvp.second] + 1;
q.push_back(make_pair(newX, newY));
}
}
}
int res = -1;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (grid[i][j] == 0 && d[i][j] <= 200)
res = max(res, d[i][j]);
}
}
return res;
}
};
// Test
intmain()
{
Solution sol;
vector<vector<int>> grid =
{
{1, 0, 1},
{0, 0, 0},
{1, 0, 1}
};
auto res = sol.maxDistance(grid);
cout << res << endl;
return0;
}