forked from garimasingh128/CP-DSA-Cpp-C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberOfIslands_DFS_solution.txt
49 lines (40 loc) · 1.4 KB
/
NumberOfIslands_DFS_solution.txt
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
//Number of Islands
//LeetCode Problem
//solution using DFS
//link to the problem: https://leetcode.com/problems/number-of-islands/
/* Given a 2d grid map of '1's (land) and '0's (water), count 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.*/
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int h=grid.size();
if(h==0)
return 0;
int w=grid[0].size();
int result=0;
for(int row=0;row<h;row++){
for(int col=0;col<w;col++){
if(grid[row][col]=='1'){
grid[row][col]=2;
result++;
dfs(grid,row, col);
}
}
}
return result;
}
void dfs(vector<vector<char>>& grid, int row, int col){
grid[row][col]=2;
if( row+1<grid.size() && grid[row+1][col]=='1'){
dfs(grid, row+1, col);
}
if(col+1<grid[0].size() && grid[row][col+1]=='1'){
dfs(grid, row, col+1);
}
if(row-1 >=0 && grid[row-1][col]=='1'){
dfs(grid,row-1,col);
}
if(col-1>=0 && grid[row][col-1]=='1'){
dfs(grid, row, col-1);
}
}
};