-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS1.cpp
88 lines (72 loc) · 2.05 KB
/
BFS1.cpp
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
84
85
86
87
88
#include <iostream>
#include <unordered_map>
#include <queue>
#include <vector>
using namespace std;
class Graph {
public:
Graph(int numVertices) : numVertices(numVertices) {
adjList.resize(numVertices);
}
void addEdge(char src, char dest) {
int srcIndex = src - 'A';
int destIndex = dest - 'A';
adjList[srcIndex].push_back(dest);
adjList[destIndex].push_back(src);
}
bool bfs(char start, char goal, unordered_map<char, char>& parent) {
int startIndex = start - 'A';
int goalIndex = goal - 'A';
vector<bool> visited(numVertices, false);
queue<char> q;
visited[startIndex] = true;
q.push(start);
while (!q.empty()) {
char current = q.front();
q.pop();
if (current == goal) {
return true;
}
for (char neighbor : adjList[current - 'A']) {
if (!visited[neighbor - 'A']) {
visited[neighbor - 'A'] = true;
parent[neighbor] = current;
q.push(neighbor);
}
}
}
return false;
}
private:
int numVertices;
vector<vector<char>> adjList;
};
int main() {
Graph graph(26);
graph.addEdge('S', 'A');
graph.addEdge('S', 'B');
graph.addEdge('A', 'F');
graph.addEdge('B', 'C');
graph.addEdge('B', 'D');
graph.addEdge('C', 'E');
graph.addEdge('D', 'F');
graph.addEdge('E', 'F');
char start = 'S';
char goal = 'F';
unordered_map<char, char> parent;
for (char c = 'A'; c <= 'Z'; c++) {
parent[c] = '\0';
}
if (graph.bfs(start, goal, parent)) {
cout << "Path found!" << endl;
cout << "Path: ";
while (goal != start) {
cout << goal << " <- ";
goal = parent[goal];
}
cout << start << endl;
} else {
cout << "No path found." << endl;
}
return 0;
}