forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0200.cpp
More file actions
executable file
·38 lines (34 loc) · 809 Bytes
/
LC0200.cpp
File metadata and controls
executable file
·38 lines (34 loc) · 809 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/number-of-islands/
Time: O(m • n)
Space: O(m • n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int numIslands(vector<vector<char>> grid) {
if (grid.empty())
return 0;
int n, m, components;
n = grid.size();
m = grid[0].size();
components = 0;
// flood-fill algorithm
function<void(int, int)> flood_fill = [&](int i, int j) {
if (i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == '0')
return;
grid[i][j] = '0';
flood_fill(i - 1, j);
flood_fill(i + 1, j);
flood_fill(i, j - 1);
flood_fill(i, j + 1);
};
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (grid[i][j] == '1') {
components++;
flood_fill(i, j);
}
return components;
}
};