|
| 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