CODE :
#include<bits/stdc++.h>
#define MAX 1000
using namespace std;
map<string,int >mymap;
map<int ,string>mymap1;
int node, edge,color[MAX],par[MAX],mat[MAX][MAX],start,end1;
void Printpath(int V)
{
if(start==V)
{
string s = mymap1[start];
cout << s;
}
else if(par[V]==0)
{
printf("No path exist\n");
}
else
{
Printpath(par[V]);
string s = mymap1[V];
cout <<"-->" << s ;
}
}
void bfs(int ux)
{
int vx,i;
color[ux]=1;
par[ux]=0;
queue<int>Q;
Q.push(ux);
while(!Q.empty())
{
vx=Q.front();
Q.pop();
for(i=1; i<=node; i++)
{
if(mat[vx][i]==1 && color[i]==0)
{
color[i]=1;
Q.push(i);
par[i]=vx;
}
}
}
}
int main()
{
int n=1;
string source,des,s,e;
cin >> node >> edge;
getchar();
for(int i=0; i<edge; i++)
{
cin >>source >>des;
if(mymap.find(source)==mymap.end())
{
mymap[source]=n;
mymap1[n]=source;
n=n+1;
}
if(mymap.find(des)==mymap.end())
{
mymap[des]=n;
mymap1[n]=des;
n=n+1;
}
int x =mymap[source];
int y =mymap[des];
mat[x][y]=1;
mat[y][x]=1;
}
cout<<"Enter a Start and End" << endl;
cin >> s >> e;
start = mymap[s];
end1 = mymap[e];
for(int i=1; i<=node; i++)
{
color[i]=0;
par[i]=0;
}
bfs(start);
cout << "PATH" << endl;
Printpath(end1);
cout << endl;
}
INPUT:
7 11
SYLHET DHAKA
SYLHET CHITTAGONG
CHITTAGONG BARISAL
CHITTAGONG DHAKA
DHAKA RAJSHAHI
DHAKA KHULNA
KHULNA RAJSHAHI
DHAKA RANGPUR
RAJSHAHI RANGPUR
KHULNA BARISAL
DHAKA BARISAL
SYLHET RANGPUR
OUTPUT:
PATH
SYLHET-->DHAKA-->RANGPUR
No comments:
Post a Comment