Leetcode 200. Number of Islands

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Number of Islands

2. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.size() == 0) {
return 0;
}
int islands = 0;
int rows = grid.size();
int columns = grid[0].size();
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(grid[i][j] == '1') {
islands++;
removeIsland(grid, i, j, rows, columns);
}
}
}
return islands;
}

private:
void removeIsland(vector<vector<char>>& grid, int i, int j, int& rows, int& columns) {
if(i < 0 || i == rows || j < 0 || j == columns || grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
removeIsland(grid, i + 1, j, rows, columns);
removeIsland(grid, i - 1, j, rows, columns);
removeIsland(grid, i, j + 1, rows, columns);
removeIsland(grid, i, j - 1, rows, columns);
}
};

Reference

  1. https://leetcode.com/problems/number-of-islands/description/
如果有收获,可以请我喝杯咖啡!