Skip to content

Commit

Permalink
Add BFS algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
vadyushkins committed Dec 18, 2023
1 parent a0a553a commit c05f08d
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions algorithms/bfs/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
target_sources(${PROJECT_NAME} PUBLIC test_bfs.cpp bfs.cpp)
22 changes: 22 additions & 0 deletions algorithms/bfs/bfs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#include "bfs.hpp"

std::vector<int64_t> bfs(
const std::vector<std::vector<int64_t>> &graph,
int64_t source_node
) {
std::size_t n = graph.size();
std::vector<int64_t> distance(n, -1);
distance[source_node] = 0;
std::deque<int64_t> 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;
}
8 changes: 8 additions & 0 deletions algorithms/bfs/bfs.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include <deque>
#include <vector>
#include <cstdint>

std::vector<int64_t> bfs(
const std::vector<std::vector<int64_t>> &graph,
int64_t source_node
);
53 changes: 53 additions & 0 deletions algorithms/bfs/test_bfs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <gtest/gtest.h>

#include "bfs.hpp"

TEST(BFS, Test0) {
std::vector<std::vector<int64_t>> graph = {
{1, 2},
{0, 2},
{0, 1},
};

int64_t source_node = 0;

std::vector<int64_t> distance = bfs(graph, 0);

std::vector<int64_t> expected_distance = {0, 1, 1};

ASSERT_EQ(distance, expected_distance);
}

TEST(BFS, Test1) {
std::vector<std::vector<int64_t>> graph = {
{1},
{2},
{},
};

int64_t source_node = 0;

std::vector<int64_t> distance = bfs(graph, 0);

std::vector<int64_t> expected_distance = {0, 1, 2};

ASSERT_EQ(distance, expected_distance);
}

TEST(BFS, Test2) {
std::vector<std::vector<int64_t>> graph = {
{1, 2},
{0, 2},
{0, 1},
{4},
{3},
};

int64_t source_node = 0;

std::vector<int64_t> distance = bfs(graph, 0);

std::vector<int64_t> expected_distance = {0, 1, 1, -1, -1};

ASSERT_EQ(distance, expected_distance);
}

0 comments on commit c05f08d

Please sign in to comment.