-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbfs.cpp
More file actions
83 lines (67 loc) · 1.68 KB
/
bfs.cpp
File metadata and controls
83 lines (67 loc) · 1.68 KB
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
#include <iostream>
#include <queue>
#include <string>
#include <bits/stdc++.h>
#include <list>
#include <vector>
using namespace std;
class vertex{
string name;
string colour;
public:
vertex(){};
vertex(string s){name=s; colour="white";}
string getName(){return name;}
string getColour(){return colour;}
void setColour(string c){colour = c;}
};
int main()
{
int n;
cout << "Enter the number of vertices: ";
cin >> n;
vector <vertex> vertices;
cout << "Enter the name of vertices" << endl;
for(int i=0; i<n; i++)
{
string name;
cin >> name;
vertices.push_back(vertex(name));
}
list <vertex *> adjlist[n];
unordered_map<string, list<vertex*>> Adj;
for(int i=0; i<n; i++)
{
cout << "Enter the number of vertices adjacent to " << vertices[i].getName() << ": " << endl;
int numOfAdjV;
cin >> numOfAdjV;
for(int j=0; j<numOfAdjV; j++)
{
cout << "Enter the name of adjacent vertex "<< j+1 << "/" << numOfAdjV << " : ";
string nameOfAdjV;
cin >> nameOfAdjV;
for(int k=0; k<n; k++)
if(nameOfAdjV == vertices[k].getName())
adjlist[i].push_back(&vertices[k]);
}
Adj[vertices[i].getName()] = adjlist[i];
}
queue<vertex *> Q;
vertices[0].setColour("black");
Q.push(&vertices[0]);
while(!Q.empty())
{
vertex *v = Q.front();
Q.pop();
for(list <vertex *> :: iterator i=Adj[v->getName()].begin(); i!=Adj[v->getName()].end(); i++)
{
if((*i)->getColour() == "white")
{
(*i)->setColour("gray");
Q.push(*i);
cout << (*i)->getName() << endl;
}
}
v->setColour("black");
}
}