forked from Anubhav-1020/Hacktoberfest-Beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIslands.cpp
83 lines (74 loc) · 1.75 KB
/
Islands.cpp
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
//Interview question solved using dfs graph traversal logic
/*
Question:
An island is a small piece of land surrounded by water .
A group of islands is said to be connected if we can reach from any given island to any other island in the same group .
Given V islands (numbered from 1 to V) and E connections or edges between islands. Can you count the number of connected groups of islands.
Input Format :
The first line of input contains two integers, that denote the value of V and E.
Each of the following E lines contains two integers, that denote that there exists an edge between vertex a and b.
Output Format :
Print the count the number of connected groups of islands
Constraints :
0 <= V <= 1000
0 <= E <= (V * (V-1)) / 2
0 <= a <= V - 1
0 <= b <= V - 1
Time Limit: 1 second
Sample Input 1:
5 8
0 1
0 4
1 2
2 0
2 4
3 0
3 2
4 3
Sample Output 1:
1
*/
//Solution code
void dfs(int **edge,int n,bool *visit,int s)
{
visit[s]=true;
for(int i=0;i<=n;i++)
{
if(edge[s][i]==1)
{
if(visit[i]==false)
{
dfs(edge,n,visit,i);
}
}
}
}
int solve(int n,int m,vector<int>u,vector<int>v)
{
int **edge=new int* [n+1];
for(int i=0;i<=n;i++)
{
edge[i]=new int[n+1];
for(int j=0;j<n;j++)
edge[i][j]=0;
}
for(int i=0;i<m;i++)
{
edge[u[i]][v[i]]=1;
edge[v[i]][u[i]]=1;
}
bool *visit=new bool[n+1];
for(int i=0;i<=n;i++)
visit[i]=false;
int count=0;
for(int i=1;i<=n;i++)
{
if(visit[i]==false)
{
dfs(edge,n,visit,i);
count+=1;
}
}
return count;
// Write your code here .
}