Skip to content

Commit 6d78a31

Browse files
committed
[feat ]: leetcode 463
Signed-off-by: Bo-Wei Chen(BWbwchen) <tim.chenbw@gmail.com>
1 parent 587cf0b commit 6d78a31

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

leetcode/0463_Island-Perimeter.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
public:
3+
vector<vector<bool>> visited;
4+
vector<pair<int, int>> ops;
5+
int island;
6+
int neigh;
7+
int max_i;
8+
int max_j;
9+
int islandPerimeter(vector<vector<int>>& grid) {
10+
visited = vector<vector<bool>>(grid.size(), vector<bool>(grid[0].size(), false));
11+
max_i = grid.size();
12+
max_j = grid[0].size();
13+
island = 0;
14+
neigh = 0;
15+
ops = {
16+
make_pair(-1, 0),
17+
make_pair(1, 0),
18+
make_pair(0, -1),
19+
make_pair(0, 1),
20+
};
21+
for (int i = 0; i < grid.size(); ++i) {
22+
for (int j = 0; j < grid[i].size(); ++j) {
23+
if (!visited[i][j])
24+
bfs(grid, i, j);
25+
}
26+
}
27+
cout << "island: " << island << ", neigh: " << neigh << endl;
28+
return island * 4 - neigh;
29+
}
30+
bool legal(int i, int j) {
31+
return i >= 0 && i < max_i && j >= 0 && j < max_j;
32+
}
33+
void bfs(vector<vector<int>>& grid, int i, int j) {
34+
queue<pair<int, int>> q;
35+
q.push(make_pair(i, j));
36+
while(!q.empty()) {
37+
auto top = q.front();
38+
q.pop();
39+
if (legal(top.first, top.second) && !visited[top.first][top.second]) {
40+
visited[top.first][top.second] = true;
41+
if (grid[top.first][top.second]) {
42+
island++;
43+
for (auto op: ops) {
44+
int new_i = top.first + op.first;
45+
int new_j = top.second + op.second;
46+
if (legal(new_i, new_j)) {
47+
cout << new_i << ", " << new_j << endl;
48+
q.push(make_pair(new_i, new_j));
49+
if (grid[new_i][new_j])
50+
neigh++;
51+
}
52+
}
53+
}
54+
}
55+
}
56+
}
57+
};

0 commit comments

Comments
 (0)