Skip to content

Commit 5138487

Browse files
committed
Solution: Number of Islands
1 parent 6570759 commit 5138487

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

number-of-islands/flynn.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* 풀이
3+
* - bfs를 활용합니다
4+
*
5+
* Big O
6+
* - M: grid의 행의 수
7+
* - N: grid의 열의 수
8+
*
9+
* - Time complexity: O(MN)
10+
* - 각 좌표는 최대 한 번씩만 조회하게 됩니다
11+
* - Space complexity: O(MN)
12+
* - 방문 여부를 기록하기 위해 visit 배열이 사용됩니다
13+
* - queue에 쌓이는 원소의 개수는 최대 MN개까지 증가할 수 있습니다
14+
*/
15+
16+
class Solution {
17+
public:
18+
int numIslands(vector<vector<char>>& grid) {
19+
int m = grid.size();
20+
int n = grid[0].size();
21+
22+
vector<vector<bool>> visit;
23+
for (int r = 0; r < m; ++r) {
24+
vector<bool> row;
25+
for (int c = 0; c < n; ++c) {
26+
row.push_back(false);
27+
}
28+
visit.push_back(row);
29+
}
30+
31+
pair<int, int> dirs[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
32+
33+
int res = 0;
34+
queue<pair<int, int>> q;
35+
for (int r = 0; r < m; ++r) {
36+
for (int c = 0; c < n; ++c) {
37+
if (visit[r][c] == false && grid[r][c] == '1') {
38+
++res;
39+
q.push({r, c});
40+
while (!q.empty()) {
41+
auto p = q.front();
42+
q.pop();
43+
for (auto dir : dirs) {
44+
pair<int, int> next = {p.first + dir.first, p.second + dir.second};
45+
if (0 <= next.first && next.first < m && 0 <= next.second && next.second < n) {
46+
if (visit[next.first][next.second] == false && grid[next.first][next.second] == '1') {
47+
q.push(next);
48+
visit[next.first][next.second] = true;
49+
}
50+
}
51+
}
52+
}
53+
}
54+
}
55+
}
56+
57+
return res;
58+
}
59+
};

0 commit comments

Comments
 (0)