diff --git a/algorithms/bfs/CMakeLists.txt b/algorithms/bfs/CMakeLists.txt new file mode 100644 index 0000000..782f066 --- /dev/null +++ b/algorithms/bfs/CMakeLists.txt @@ -0,0 +1 @@ +target_sources(${PROJECT_NAME} PUBLIC test_bfs.cpp bfs.cpp) \ No newline at end of file diff --git a/algorithms/bfs/bfs.cpp b/algorithms/bfs/bfs.cpp new file mode 100644 index 0000000..5cff6d8 --- /dev/null +++ b/algorithms/bfs/bfs.cpp @@ -0,0 +1,22 @@ +#include "bfs.hpp" + +std::vector bfs( + const std::vector> &graph, + int64_t source_node +) { + std::size_t n = graph.size(); + std::vector distance(n, -1); + distance[source_node] = 0; + std::deque queue = {source_node}; + while (false == queue.empty()) { + int64_t u = queue.front(); + queue.pop_front(); + for (int64_t v : graph[u]) { + if (-1 == distance[v]) { + distance[v] = distance[u] + 1; + queue.push_back(v); + } + } + } + return distance; +} \ No newline at end of file diff --git a/algorithms/bfs/bfs.hpp b/algorithms/bfs/bfs.hpp new file mode 100644 index 0000000..37971ae --- /dev/null +++ b/algorithms/bfs/bfs.hpp @@ -0,0 +1,8 @@ +#include +#include +#include + +std::vector bfs( + const std::vector> &graph, + int64_t source_node +); \ No newline at end of file diff --git a/algorithms/bfs/test_bfs.cpp b/algorithms/bfs/test_bfs.cpp new file mode 100644 index 0000000..4319953 --- /dev/null +++ b/algorithms/bfs/test_bfs.cpp @@ -0,0 +1,53 @@ +#include + +#include "bfs.hpp" + +TEST(BFS, Test0) { + std::vector> graph = { + {1, 2}, + {0, 2}, + {0, 1}, + }; + + int64_t source_node = 0; + + std::vector distance = bfs(graph, 0); + + std::vector expected_distance = {0, 1, 1}; + + ASSERT_EQ(distance, expected_distance); +} + +TEST(BFS, Test1) { + std::vector> graph = { + {1}, + {2}, + {}, + }; + + int64_t source_node = 0; + + std::vector distance = bfs(graph, 0); + + std::vector expected_distance = {0, 1, 2}; + + ASSERT_EQ(distance, expected_distance); +} + +TEST(BFS, Test2) { + std::vector> graph = { + {1, 2}, + {0, 2}, + {0, 1}, + {4}, + {3}, + }; + + int64_t source_node = 0; + + std::vector distance = bfs(graph, 0); + + std::vector expected_distance = {0, 1, 1, -1, -1}; + + ASSERT_EQ(distance, expected_distance); +} \ No newline at end of file