UVA 459 Graph Connectivity Solution
Solution in C++:
///**********ALLAH IS ALMIGHTY************///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
#include<bits/stdc++.h>
using namespace std;
vector<int>g[1000];
bool visited[1000];
void dfs(int s)
{
visited[s]=1;
for(int i=0; i<g[s].size(); i++)
{
int x=g[s][i];
if(visited[x]==0)
{
dfs(x);
}
}
}
int main()
{
int n,m,i,j,t,u,v,cn;
char c[2],s[15];
scanf("%d\n",&t);
while(t--)
{
gets(c);
n=c[0]-64;
while(gets(s))
{
if(s[0]=='\0')
break;
u=s[0]-65;
v=s[1]-65;
g[u].push_back(v);
g[v].push_back(u);
}
cn=0;
memset(visited,0,sizeof visited);
for(int i=0; i<n; i++)
{
if(visited[i]==0)
{
dfs(i);
cn++;
}
}
if(t==0)
cout<<cn<<endl;
else
cout<<cn<<endl<<endl;
for(int i=0; i<n; i++)
g[i].clear();
}
}
///**********ALLAH IS ALMIGHTY************///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
#include<bits/stdc++.h>
using namespace std;
vector<int>g[1000];
bool visited[1000];
void dfs(int s)
{
visited[s]=1;
for(int i=0; i<g[s].size(); i++)
{
int x=g[s][i];
if(visited[x]==0)
{
dfs(x);
}
}
}
int main()
{
int n,m,i,j,t,u,v,cn;
char c[2],s[15];
scanf("%d\n",&t);
while(t--)
{
gets(c);
n=c[0]-64;
while(gets(s))
{
if(s[0]=='\0')
break;
u=s[0]-65;
v=s[1]-65;
g[u].push_back(v);
g[v].push_back(u);
}
cn=0;
memset(visited,0,sizeof visited);
for(int i=0; i<n; i++)
{
if(visited[i]==0)
{
dfs(i);
cn++;
}
}
if(t==0)
cout<<cn<<endl;
else
cout<<cn<<endl<<endl;
for(int i=0; i<n; i++)
g[i].clear();
}
}
No comments