Skip to content

Commit e2721b1

Browse files
authored
adds week7
1 parent 6dd8755 commit e2721b1

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

โ€Žnumber-of-islands/yeonguchoe.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
class Solution {
2+
public:
3+
int numIslands(vector<vector<char>>& grid) {
4+
int count = 0;
5+
6+
int row_size = grid.size();
7+
int column_size = grid[0].size();
8+
9+
queue<pair<int, int>> q;
10+
11+
for (int i = 0; i < row_size; i++) {
12+
for (int j = 0; j < column_size; j++) {
13+
if (grid[i][j] == '1') {
14+
LookAround(i, j, grid, q, row_size, column_size);
15+
count += 1;
16+
}
17+
}
18+
}
19+
return count;
20+
}
21+
22+
// BFS
23+
void LookAround(int& x, int& y, vector<vector<char>>& grid,
24+
queue<pair<int, int>>& q, int& row_size, int& column_size) {
25+
pair<int, int> center_location{x, y};
26+
q.push(center_location);
27+
28+
grid[x][y] = '0';
29+
30+
while (!q.empty()) {
31+
pair<int, int> selected_location = q.front();
32+
q.pop();
33+
34+
int selected_x = selected_location.first;
35+
int selected_y = selected_location.second;
36+
37+
// ์„ ํƒ๋œ cell์—์„œ ์™ผ์ชฝ
38+
if (selected_x - 1 >= 0 &&
39+
grid[selected_x - 1][selected_y] == '1') {
40+
q.push({selected_x - 1, selected_y});
41+
grid[selected_x - 1][selected_y] = '0';
42+
}
43+
44+
// ์„ ํƒ๋œ cell์—์„œ ์˜ค๋ฅธ์ชฝ
45+
if (selected_x + 1 < row_size &&
46+
grid[selected_x + 1][selected_y] == '1') {
47+
q.push({selected_x + 1, selected_y});
48+
grid[selected_x + 1][selected_y] = '0';
49+
}
50+
51+
// ์„ ํƒ๋œ cell์—์„œ ์œ„์ชฝ
52+
if (selected_y - 1 >= 0 &&
53+
grid[selected_x][selected_y - 1] == '1') {
54+
q.push({selected_x, selected_y - 1});
55+
grid[selected_x][selected_y - 1] = '0';
56+
}
57+
58+
// ์„ ํƒ๋œ cell์—์„œ ์•„๋ž˜์ชฝ
59+
if (selected_y + 1 < column_size &&
60+
grid[selected_x][selected_y + 1] == '1') {
61+
q.push({selected_x, selected_y + 1});
62+
grid[selected_x][selected_y + 1] = '0';
63+
}
64+
}
65+
}
66+
// ์‹œ๊ฐ„ ๋ณต์žก๋„: O(row*column)
67+
// ๊ณต๊ฐ„ ๋ณต์žก๋„: O(row*column)
68+
};

0 commit comments

Comments
ย (0)