Problem : First you have to store a graph in a adjacency list.Then you have to determine the shortest distance between source and destination node.
Problem link and solution idea : http://www.shafaetsplanet.com/planetcoding/?p=604
Source code :
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Eenter node and edge number : ";
int node,edge;
cin>>node>>edge;
vector<int>v[100];
int i;
int a,b;
cout<<"Enter nodes connecting edges : "<<endl;
for(i=1; i<=edge; i++)
{
cin>>a>>b;
v[a].push_back(b);
}
cout<<endl;
int source,destination;
while(1)
{
cout<<"Source : ";
cin>>source;
cout<<"destination : ";
cin>>destination;
int visited[100];
memset(visited,-1,sizeof(visited));
queue<int>q;
q.push(source);
visited[source]=0;
int u,p;
while(!q.empty())
{
u=q.front();
q.pop();
for(i=0; i<v[u].size(); i++)
{
p=v[u][i];
if(visited[p]==-1)
{
visited[p]=visited[u]+1;
q.push(p);
if(p==destination) break;
}
}
}
cout<<"Shortest distance betwwen destination and source : ";
cout<<visited[destination]-visited[source]<<endl<<endl;
}
return 0;
}
Problem link and solution idea : http://www.shafaetsplanet.com/planetcoding/?p=604
Source code :
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Eenter node and edge number : ";
int node,edge;
cin>>node>>edge;
vector<int>v[100];
int i;
int a,b;
cout<<"Enter nodes connecting edges : "<<endl;
for(i=1; i<=edge; i++)
{
cin>>a>>b;
v[a].push_back(b);
}
cout<<endl;
int source,destination;
while(1)
{
cout<<"Source : ";
cin>>source;
cout<<"destination : ";
cin>>destination;
int visited[100];
memset(visited,-1,sizeof(visited));
queue<int>q;
q.push(source);
visited[source]=0;
int u,p;
while(!q.empty())
{
u=q.front();
q.pop();
for(i=0; i<v[u].size(); i++)
{
p=v[u][i];
if(visited[p]==-1)
{
visited[p]=visited[u]+1;
q.push(p);
if(p==destination) break;
}
}
}
cout<<"Shortest distance betwwen destination and source : ";
cout<<visited[destination]-visited[source]<<endl<<endl;
}
return 0;
}
No comments:
Post a Comment