-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS4.cpp
109 lines (83 loc) · 2.69 KB
/
BFS4.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <iostream>
#include <unordered_map>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
class Graph {
public:
Graph(int numVertices) : numVertices(numVertices) {
adjList.resize(numVertices);
}
void addEdge(char src, char dest, int cost) {
int srcIndex = src - 'A';
int destIndex = dest - 'A';
adjList[srcIndex].push_back(make_pair(dest, cost));
adjList[destIndex].push_back(make_pair(src, cost));
}
bool bfs(char start, char goal, unordered_map<char, char>& parent) {
int startIndex = start - 'A';
int goalIndex = goal - 'A';
vector<bool> visited(numVertices, false);
priority_queue<pair<int, char>, vector<pair<int, char>>, greater<pair<int, char>>> pq;
pq.push(make_pair(0, start));
while (!pq.empty()) {
char current = pq.top().second;
int currentCost = pq.top().first;
pq.pop();
if (current == goal) {
return true;
}
if (visited[current - 'A']) {
continue;
}
visited[current - 'A'] = true;
for (const auto& edge : adjList[current - 'A']) {
char neighbor = edge.first;
int edgeCost = edge.second;
if (!visited[neighbor - 'A']) {
int newCost = currentCost + edgeCost;
pq.push(make_pair(newCost + heuristic(neighbor, goal), neighbor));
parent[neighbor] = current;
}
}
}
return false;
}
private:
int numVertices;
vector<vector<pair<char, int>>> adjList;
int heuristic(char current, char goal) {
int currentX = current - 'A';
int goalX = goal - 'A';
return abs(currentX - goalX);
}
};
int main() {
Graph graph(26);
graph.addEdge('S', 'A', 1);
graph.addEdge('S', 'D', 5);
graph.addEdge('A', 'B', 3);
graph.addEdge('B', 'C', 1);
graph.addEdge('B', 'G', 1);
graph.addEdge('C', 'G', 1);
graph.addEdge('D', 'G', 1);
char start = 'S';
char goal = 'G';
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;
}