-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectedIslands.cpp
More file actions
43 lines (38 loc) · 1.36 KB
/
Copy pathConnectedIslands.cpp
File metadata and controls
43 lines (38 loc) · 1.36 KB
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
//Here connected means connection in North south east west in leetcode, in geeks for geeks all 8 sides .
class Solution {
public:
int c = 0, ro, co;
bool isSafe(vector < vector < char >> & grid, int i, int j) {//Remember&
if (i >= 0 and i < ro and j >= 0 and j < co)
return (grid[i][j] == '1');
else
return false;
}
void dfs(vector < vector < char >> & grid, int i, int j) {
static int u[] = {-1, 1, 0, 0 }; //NSWE
static int d[] = {0,0,-1,1};
grid[i][j] = '2'; //To mark as visited using vis array will give TLE
for (int k = 0; k < 4; k++) {
if (isSafe(grid, (i + u[k]), (j + d[k])))
dfs(grid, (i + u[k]), (j + d[k]));
}
}
int numIslands(vector < vector < char >> & grid) {
if ((int) grid.size() == 0) //if input is empty this condition is mandatory
return 0;
int col = grid[0].size(), row = grid.size();
ro = row;
co = col;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
c++;
}
}
}
return c;
}
};
//https://leetcode.com/problems/number-of-islands/submissions/
//https://www.geeksforgeeks.org/find-number-of-islands/