|
| 1 | +#include "0200_number_of_islands.h" |
1 | 2 | #include <iostream> |
2 | 3 | #include <vector> |
3 | 4 |
|
4 | 5 | using std::cout; |
5 | 6 | using std::vector; |
6 | 7 |
|
7 | | -class Solution { |
8 | | -private: |
9 | | - void dfs(vector<vector<char>> &grid, size_t row, size_t column) { |
10 | | - if (row >= grid.size() || column >= grid[row].size() || |
11 | | - grid[row][column] == '0') { |
12 | | - return; |
13 | | - } |
14 | | - |
15 | | - grid[row][column] = '0'; |
16 | | - dfs(grid, row + 1, column); |
17 | | - dfs(grid, row, column + 1); |
18 | | - dfs(grid, row - 1, column); |
19 | | - dfs(grid, row, column - 1); |
| 8 | +void dfs(vector<vector<char>> &grid, size_t row, size_t column) { |
| 9 | + if (row >= grid.size() || column >= grid[row].size() || |
| 10 | + grid[row][column] == '0') { |
| 11 | + return; |
20 | 12 | } |
21 | 13 |
|
22 | | -public: |
23 | | - int numIslands(vector<vector<char>> &grid) { |
24 | | - int islands = 0; |
25 | | - for (int row = 0; row < grid.size(); row++) { |
26 | | - for (int column = 0; column < grid[row].size(); column++) { |
27 | | - if (grid[row][column] == '1') { |
28 | | - islands++; |
29 | | - dfs(grid, row, column); |
30 | | - } |
| 14 | + grid[row][column] = '0'; |
| 15 | + dfs(grid, row + 1, column); |
| 16 | + dfs(grid, row, column + 1); |
| 17 | + dfs(grid, row - 1, column); |
| 18 | + dfs(grid, row, column - 1); |
| 19 | +} |
| 20 | + |
| 21 | +int Solution::numIslands(vector<vector<char>> &grid) { |
| 22 | + int islands = 0; |
| 23 | + for (int row = 0; row < grid.size(); row++) { |
| 24 | + for (int column = 0; column < grid[row].size(); column++) { |
| 25 | + if (grid[row][column] == '1') { |
| 26 | + islands++; |
| 27 | + dfs(grid, row, column); |
31 | 28 | } |
32 | 29 | } |
33 | | - |
34 | | - return islands; |
35 | 30 | } |
36 | | -}; |
37 | | - |
38 | | -int main() { |
39 | | - vector<vector<char>> grid = {{'1', '1', '1', '1', '0'}, |
40 | | - {'1', '1', '0', '1', '0'}, |
41 | | - {'1', '1', '0', '0', '0'}, |
42 | | - {'0', '0', '0', '0', '0'}}; |
43 | 31 |
|
44 | | - cout << Solution().numIslands(grid); |
| 32 | + return islands; |
45 | 33 | } |
0 commit comments