Website Summary Files Commits Branches @commit @diff @stats
path: root / Seminar11 / bfs-dfs.cpp
diff options
context:
space:
mode:
Commit750de18faa33ae862a3348a6679f32e1517a3d4b (patch)
Author
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-12-21 18:44:34 +0200
Committer
 Stoycho Kyosev <stoycho.kk@gmail.com>
2022-12-21 18:44:34 +0200
Files281c8c52621b86185f755936e8b1c46287ca3ae0 /Seminar11/bfs-dfs.cpp
Data-structures-and-algorithms-750de18faa33ae862a3348a6679f32e1517a3d4b.tar
Data-structures-and-algorithms-750de18faa33ae862a3348a6679f32e1517a3d4b.tar.gz
Data-structures-and-algorithms-750de18faa33ae862a3348a6679f32e1517a3d4b.zip
Parentc1b3267208163f17c08d545f805f0b412d35d377 (diff)
add Seminar11
1 files changed, 64 insertions, 0 deletions
-rw-r--r--Seminar11/bfs-dfs.cpp64
diff --git a/Seminar11/bfs-dfs.cpp b/Seminar11/bfs-dfs.cpp
new file mode 100644
index 0000000..a19abcd
--- /dev/null
+++ b/Seminar11/bfs-dfs.cpp
@@ -0,0 +1,64 @@
+#include<iostream>
+#include"Graph-Impl/AdjacencyListGraph/AdjListGraph.h"
+#include"Graph-Impl/MatrixGraph/MatrixGraph.h"
+#include<queue>
+
+void BFS(const MatrixGraph& g, MatrixGraph::vertex_t start) {
+ std::vector<bool> visited(g.vertexCount(), false);
+
+ std::queue<MatrixGraph::vertex_t> q;
+
+ q.push(start);
+
+ while(!q.empty()) {
+ MatrixGraph::vertex_t current = q.front();
+ q.pop();
+
+ if(visited[current])
+ continue;
+
+ visited[current] = true;
+
+ std::cout << current << " ";
+
+ auto successors = g.getSuccessors(current);
+
+ for(const auto& edge : successors) {
+ if(!visited[edge])
+ q.push(edge);
+ }
+ }
+}
+
+void DFSRec(std::vector<bool>& visited, const AdjListGraph& g, AdjListGraph::vertex_t start) {
+ visited[start] = true;
+
+ auto child = g.adjacent(start);
+
+ std::cout << "Visited " << start << std::endl;
+
+ for(const auto& currChild : child) {
+ if(!visited[currChild.to]) {
+ DFSRec(visited, g, currChild.to);
+ }
+ }
+}
+
+void DFS(const AdjListGraph& g, AdjListGraph::vertex_t start) {
+ std::vector<bool> visited(g.vertexCount(), false);
+ DFSRec(visited, g, start);
+}
+
+int main() {
+ MatrixGraph g(5);
+ // AdjListGraph g(5);
+ g.addEdge(0, 2, 1);
+ g.addEdge(0, 3, 1);
+ g.addEdge(0, 1, 1);
+ g.addEdge(2, 3, 1);
+ g.addEdge(1, 4, 1);
+ g.addEdge(3, 4, 1);
+ g.addEdge(1, 3, 1);
+
+ BFS(g, 0);
+} \ No newline at end of file