#include<bits/stdc++.h>
using namespace std;
vector<int>v[100];
int i,j,m,n,k,a,b;
int color[100],parent[100],time,starttime[100],endtime[100];
void dfs_visit(int x)
{
time++;
color[x]=0;
starttime[x]=time;
for(j=0;j<v[x].size();j++)
{
y=v[x][j];
if(color[y]!=-1)
{
parent[y]=x;
dfs_visit(y);
}
}
color[x]=1;
time++;
endtime[x]=time;
}
void dfs()
{
for(i=0;i<100;i++)
{
color[i]=-1;
parent[i]=-1;
}
time=0;
for(i=0;i<n;i++)
{
if(color[i]==-1) dfs(i);
}
}
int main()
{
cout<<"enter the number of edges and nodes"<<endl;
cin>>m>>n;
cout<<"enter the edges"<<endl;
for(i=1;i<=m;i++)
{
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
cout<<"enter source"<<endl;
int s;
cin>>s;
bfs(s);
}
Sunday, October 1, 2017
bfs(breadth first search)
#include<bits/stdc++.h>
using namespace std;
vector<int>v[100];
int i,j,m,n,k,a,b;
int color[100],d[100],parent[100];
void bfs(int s)
{
for(i=1;i<=n;i++) {
color[i]=-1;
parent[i]=-1;
}
color[s]=0;
d[s]=0;
parent[s]=s;
queue<int>q;
q.push(s);
while(!q.empty())
{
int x=q.front();
q.pop();
for(i=0;i<v[x].size();i++)
{
int y=v[x][i];
if(color[y]==-1)
{
color[y]=0;
d[y]=d[x]+1;
q.push(y);
parent[y]=x;
}
}
color[x]=1;
}
}
int main()
{
cout<<"enter the number of edges and nodes"<<endl;
cin>>m>>n;
cout<<"enter the edges"<<endl;
for(i=1;i<=m;i++)
{
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
cout<<"enter source"<<endl;
int s;
cin>>s;
bfs(s);
}
using namespace std;
vector<int>v[100];
int i,j,m,n,k,a,b;
int color[100],d[100],parent[100];
void bfs(int s)
{
for(i=1;i<=n;i++) {
color[i]=-1;
parent[i]=-1;
}
color[s]=0;
d[s]=0;
parent[s]=s;
queue<int>q;
q.push(s);
while(!q.empty())
{
int x=q.front();
q.pop();
for(i=0;i<v[x].size();i++)
{
int y=v[x][i];
if(color[y]==-1)
{
color[y]=0;
d[y]=d[x]+1;
q.push(y);
parent[y]=x;
}
}
color[x]=1;
}
}
int main()
{
cout<<"enter the number of edges and nodes"<<endl;
cin>>m>>n;
cout<<"enter the edges"<<endl;
for(i=1;i<=m;i++)
{
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
cout<<"enter source"<<endl;
int s;
cin>>s;
bfs(s);
}
Subscribe to:
Posts (Atom)