Lesson Overview

Welcome to our session on Graph Algorithms Implementation. A large proportion of real-world problems, from social networking to routing applications, can be represented by graphs. Understanding and implementing graph algorithms is thus a key skill to have in your programming toolkit. In this lesson, we introduce and explore one of the most fundamental graph traversal algorithms — the Breadth-First Search (BFS).

Quick Example

Let's take a sneak peek at the BFS algorithm. Given a graph and a starting vertex, BFS systematically explores the edges of the graph to "visit" each reachable vertex. It does this by managing a queue of vertices yet to be explored and consistently visiting all vertices adjacent to the current one before moving on. BFS is particularly efficient because it can find the shortest distance between the starting vertex and all other vertices in a graph.

Here's a sample BFS algorithm implemented in C# that we will dissect in depth and master:

using System;
using System.Collections.Generic;

public class Graph
{
    // Dictionary to store adjacency list of the graph
    private Dictionary<int, List<int>> adjList = new Dictionary<int, List<int>>();

    public void AddEdge(int src, int dest)
    {
        if (!adjList.ContainsKey(src))
        {
            adjList[src] = new List<int>();
        }
        if (!adjList.ContainsKey(dest))
        {
            adjList[dest] = new List<int>();
        }
        adjList[src].Add(dest);
        adjList[dest].Add(src);
    }

    // Method to perform Breadth-First Search from a given starting vertex
    public List<int> Bfs(int start)
    {
        var visited = new HashSet<int>();
        var queue = new Queue<int>();
        var result = new List<int>();

        queue.Enqueue(start); // Start the BFS with the starting vertex

        while (queue.Count > 0)
        {
            int node = queue.Dequeue(); // Remove the vertex at the front of the queue
            if (!visited.Contains(node))
            {
                visited.Add(node);
                result.Add(node);
                foreach (var neighbor in adjList[node])
                {
                    // Add unvisited neighbors to the queue
                    if (!visited.Contains(neighbor))
                    {
                        queue.Enqueue(neighbor);
                    }
                }
            }
        }

        return result;
    }

    public static void Main(string[] args)
    {
        Graph graph = new Graph();
        // Create graph by adding edges between vertices
        graph.AddEdge(0, 1);
        graph.AddEdge(0, 2);
        graph.AddEdge(1, 2);
        graph.AddEdge(2, 0); // multi-edge between 0 and 2
        graph.AddEdge(2, 3);
        graph.AddEdge(3, 3);

        Console.WriteLine("BFS traversal starting from node 2:");
        // Perform BFS starting from vertex 2 and print the result
        Console.WriteLine(string.Join(", ", graph.Bfs(2)));
    }
}
What's Next?

As we delve into this session, we will understand the mechanics behind BFS. Our study will include the concepts of traversal, the queue data structure's usefulness in BFS, and how to handle the discovery and processing of nodes. Equipped with these fundamentals, we'll practice on a variety of problems calling for BFS to perform node-level searches or find connected components in a graph. Let's dive in and uncover the power of graph algorithms!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal