-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuninformed_cpp_BFS.cpp
More file actions
106 lines (84 loc) · 2.19 KB
/
Copy pathuninformed_cpp_BFS.cpp
File metadata and controls
106 lines (84 loc) · 2.19 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Uninformed Search: BFS
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
static std::vector<int> bfs_path(const std::vector<std::vector<int>>& graph, int start, int goal) {
int n = (int)graph.size();
std::vector<int> prev(n, -1);
std::vector<bool> visited(n, false);
std::queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int u = q.front();
q.pop();
if (u == goal) break;
for (int v : graph[u]) {
if (!visited[v]) {
visited[v] = true;
prev[v] = u;
q.push(v);
}
}
}
if (!visited[goal]) return {};
std::vector<int> path;
for (int at = goal; at != -1; at = prev[at]) path.push_back(at);
std::reverse(path.begin(), path.end());
return path;
}
int main() {
std::vector<std::vector<int>> graph = {
{1, 2}, // 0
{3, 4}, // 1
{5}, // 2
{6}, // 3
{6}, // 4
{6}, // 5
{} // 6
};
int start = 0, goal = 6;
auto path = bfs_path(graph, start, goal);
if (path.empty()) {
std::cout << "No path\n";
return 0;
}
std::cout << "BFS Path: ";
for (size_t i = 0; i < path.size(); i++) {
if (i) std::cout << " -> ";
std::cout << path[i];
}
std::cout << "\n";
return 0;
}
// #include <bits/stdc++.h>
// using namespace std;
// void bfs(int start, vector<vector<int>>& graph) {
// vector<bool> visited(graph.size(), false);
// queue<int> q;
// visited[start] = true;
// q.push(start);
// while (!q.empty()) {
// int node = q.front();
// q.pop();
// cout << node << " ";
// for (int neighbor : graph[node]) {
// if (!visited[neighbor]) {
// visited[neighbor] = true;
// q.push(neighbor);
// }
// }
// }
// }
// int main() {
// int n = 5;
// vector<vector<int>> graph(n);
// graph[0] = {1, 2};
// graph[1] = {3};
// graph[2] = {};
// graph[3] = {4};
// graph[4] = {};
// bfs(0, graph);
// return 0;
// }