Skip to content

Commit 3ef1bb6

Browse files
committed
added number of islands question
1 parent 56c1fa2 commit 3ef1bb6

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

C++/number-of-islands.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public:
3+
bool visited[300][300];
4+
int r[4] = {-1,0,0,1};
5+
int c[4] = {0,-1,1,0};
6+
bool val(int row,int col,vector<vector<char>>& grid,int M,int N)
7+
{
8+
return (row<M && col<N && row>=0 && col>=0 && !visited[row][col] && grid[row][col]=='1');
9+
}
10+
void dfs(int i,int j,vector<vector<char>>& grid, int M, int N)
11+
{
12+
visited[i][j] = true;
13+
for(int a=0;a<4;a++)
14+
{
15+
int row = i + r[a];
16+
int col = j + c[a];
17+
if(val(row,col,grid,M,N))
18+
{
19+
dfs(row,col,grid,M,N);
20+
}
21+
}
22+
}
23+
int numIslands(vector<vector<char>>& grid) {
24+
int m = grid.size();
25+
int n = grid[0].size();
26+
memset(visited,0,sizeof(visited));
27+
int island_count = 0;
28+
for(int i=0;i<m;i++)
29+
{
30+
for(int j=0;j<n;j++)
31+
{
32+
if(!visited[i][j] && grid[i][j]=='1')
33+
{
34+
dfs(i,j,grid,m,n);
35+
island_count++;
36+
}
37+
}
38+
}
39+
return island_count;
40+
}
41+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,7 @@ DISCLAIMER: This above mentioned resources have affiliate links, which means if
500500
| [Sachin_Upadhyay](https://github.com/sachsbu) <br> <img src="https://avatars.githubusercontent.com/u/24941685?v=4" width="100" height="100"> | India | Java | [GitHub](https://github.com/sachsbu) |
501501
| [Amisha Sahu](https://github.com/Amisha328) <br> <img src = "https://avatars.githubusercontent.com/u/58816552?v=4" width="100" height="100"> | India | C++ | [CodeChef](https://www.codechef.com/users/amisha328)<br/>[LeetCode](https://leetcode.com/Mishi328/)<br/>[HackerRank](https://www.hackerrank.com/amishasahu328)
502502
<br/>
503+
| [Shrimadh V Rao](https://github.com/Shrimadh) <br> <img src="https://avatars.githubusercontent.com/u/64469917?v=4" width="100" height="100"> | India | C++ | [GitHub](https://github.com/Shrimadh)
503504
<div align="right">
504505
<b><a href="#algorithms">⬆️ Back to Top</a></b>
505506
</div>

0 commit comments

Comments
 (0)