ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Graph BFS Traversal

C++

Goal -- WPM

Ready
Exercise Algorithm Area
1#include <vector>
2#include <queue>
3#include <unordered_set>
4#include <iostream>
5#include <map>
6
7// Represents a graph using an adjacency list
8class Graph {
9public:
10// Map to store adjacency list: vertex -> list of neighbors
11std::map<int, std::vector<int>> adj;
12
13// Function to add an edge to the graph
14void addEdge(int u, int v)
15{
16adj[u].push_back(v);
17// For an undirected graph, add the reverse edge as well
18adj[v].push_back(u);
19}
20
21// Helper function for BFS traversal
22void bfsHelper(int startNode, std::unordered_set<int>& visited, std::queue<int>& q)
23{
24visited.insert(startNode);
25q.push(startNode);
26
27while (!q.empty())
28{
29int currentNode = q.front();
30q.pop();
31
32// Process the current node (e.g., print it)
33// std::cout << currentNode << " ";
34
35// Explore neighbors
36if (adj.count(currentNode))
37{
38for (int neighbor : adj[currentNode])
39{
40if (visited.find(neighbor) == visited.end())
41{
42visited.insert(neighbor);
43q.push(neighbor);
44}
45}
46}
47}
48}
49
50// Main BFS function
51void bfs(int startNode)
52{
53// Handle case where startNode is not in the graph
54if (adj.find(startNode) == adj.end() && !adj.empty())
55{
56std::cerr << "Start node not found in graph." << std::endl;
57return;
58}
59// Handle empty graph
60if (adj.empty())
61{
62std::cout << "Graph is empty." << std::endl;
63return;
64}
65
66std::unordered_set<int> visited;
67std::queue<int> q;
68
69bfsHelper(startNode, visited, q);
70std::cout << std::endl;
71}
72
73// Function to find shortest path using BFS
74int shortestPath(int startNode, int endNode)
75{
76// Handle invalid start or end nodes
77if (adj.find(startNode) == adj.end() || adj.find(endNode) == adj.end())
78{
79return -1; // Nodes not in graph
80}
81// Handle start and end nodes being the same
82if (startNode == endNode)
83{
84return 0;
85}
86
87std::queue<std::pair<int, int>> q;
88std::unordered_set<int> visited;
89
90q.push({startNode, 0}); // {node, distance}
91visited.insert(startNode);
92
93while (!q.empty())
94{
95int currentNode = q.front().first;
96int distance = q.front().second;
97q.pop();
98
99if (adj.count(currentNode))
100{
101for (int neighbor : adj[currentNode])
102{
103if (visited.find(neighbor) == visited.end())
104{
105if (neighbor == endNode)
106{
107return distance + 1;
108}
109visited.insert(neighbor);
110q.push({neighbor, distance + 1});
111}
112}
113}
114}
115
116return -1; // Path not found
117}
118};
119
120int main()
121{
122Graph g;
123g.addEdge(0, 1);
124g.addEdge(0, 2);
125g.addEdge(1, 2);
126g.addEdge(2, 0);
127g.addEdge(2, 3);
128g.addEdge(3, 3);
129
130std::cout << "BFS starting from node 2: ";
131g.bfs(2);
132
133std::cout << "Shortest path from 0 to 3: " << g.shortestPath(0, 3) << std::endl;
134std::cout << "Shortest path from 3 to 0: " << g.shortestPath(3, 0) << std::endl;
135std::cout << "Shortest path from 0 to 0: " << g.shortestPath(0, 0) << std::endl;
136
137Graph emptyGraph;
138std::cout << "BFS on empty graph: ";
139emptyGraph.bfs(0);
140std::cout << "Shortest path in empty graph: " << emptyGraph.shortestPath(0, 1) << std::endl;
141
142return 0;
143}
Algorithm description viewbox

Graph BFS Traversal

Algorithm description:

This C++ code implements Breadth-First Search (BFS) for a graph represented by an adjacency list. BFS systematically explores a graph level by level, making it ideal for finding the shortest path in terms of the number of edges between two nodes. This is widely used in network routing, social network analysis, and finding the minimum number of steps to reach a state in a puzzle.

Algorithm explanation:

The `Graph` class uses `std::map` for its adjacency list, where keys are nodes and values are vectors of their neighbors. The `bfs` function initiates the traversal from a `startNode`. It uses a `std::queue` to manage nodes to visit and an `std::unordered_set` to keep track of visited nodes, preventing cycles and redundant processing. The `bfsHelper` function performs the core traversal, adding the start node to the queue and visited set, then iteratively dequeuing a node, processing it, and enqueuing its unvisited neighbors. The `shortestPath` function extends BFS to find the minimum number of edges between two nodes. It stores pairs of {node, distance} in the queue and returns the distance when the `endNode` is reached. The time complexity for BFS is O(V + E), where V is the number of vertices and E is the number of edges, as each vertex and edge is visited at most once. The space complexity is O(V) in the worst case for the queue and visited set. Edge cases include empty graphs, disconnected components, and invalid start/end nodes.

Pseudocode:

class Graph:
  adjacency_list

  function addEdge(u, v):
    add v to adjacency_list[u]
    add u to adjacency_list[v] // for undirected graph

  function bfs(start_node):
    if graph is empty:
      return
    if start_node not in graph:
      print error
      return

    visited = empty set
    queue = empty queue

    add start_node to visited
    enqueue start_node into queue

    while queue is not empty:
      current_node = dequeue from queue
      // process current_node
      for each neighbor of current_node:
        if neighbor is not in visited:
          add neighbor to visited
          enqueue neighbor into queue

  function shortestPath(start_node, end_node):
    if start_node or end_node not in graph:
      return -1
    if start_node == end_node:
      return 0

    queue = empty queue of {node, distance}
    visited = empty set

    enqueue {start_node, 0} into queue
    add start_node to visited

    while queue is not empty:
      current_node, distance = dequeue from queue
      for each neighbor of current_node:
        if neighbor is not in visited:
          if neighbor == end_node:
            return distance + 1
          add neighbor to visited
          enqueue {neighbor, distance + 1} into queue

    return -1 // path not found