island count
2022-09-21 / Junsu Shen

200. Number of Islands

Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example
1
2
3
4
5
6
7
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Solution O(n^2)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
#include <unordered_map>
#include <string>

using namespace std;

class Solution {
int cnt;
public:
int m;
int island;
unordered_map<int, int> map;

void helper(int row, int col, vector<vector<char>>& grid)
{
if(row<0 || row>= grid.size() || col<0 || col>=grid[0].size() || grid[row][col]=='0') return;
if(grid[row][col]=='1')
{
cnt++;
grid[row][col] = '0';
helper(row-1, col, grid);
helper(row, col-1, grid);
helper(row+1, col, grid);
helper(row, col+1, grid);
}
return;
}

int numIslands(vector<vector<char>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
m =0;
island = 0;
for(int row = 0; row < rows; row++)
{
for(int col = 0; col < cols; col++)
{
if(grid[row][col]=='1')
{
island++;
cnt=0;
helper(row, col, grid);
m = max(cnt, m);
if(map.find(cnt) == map.end()) {
map[cnt] = 1;
} else {
map[cnt]++;
}
}
}
}
return island;
}
};

int main () {
Solution s;
vector<vector<char>> m
{
{'1','0','1','0','1'},
{'1','1','0','1','0'},
{'1','1','0','1','1'},
{'0','0','0','0','1'}
};


// for (auto row : m) {
// for (auto col: row)
// cout<< col <<" ";
// cout<<endl;
// }

cout<<"island cnt: "<<s.numIslands(m)<<endl;
cout<<"max island: "<<s.m<<endl;
cout<<"island shape map: "<<endl;
for (auto item: s.map) {
cout<<"shape: "<< item.first<<", cnt: "<< item.second<<endl;
}


return 0;
}
PermaLink:
https://jssu.github.io/2022/09/21/island-count/