Roadmap › Coding Round Practice (DSA in C#) › Module: Trees and Graphs
Lessons in this course (14)

14. Graph BFS and DFS

AdvancedMediumLesson 14 of 14
csharp
// Number of islands in a grid — DFS flood fill O(rows*cols)
static int Islands(char[][] g)
{
    int count = 0;
    void Sink(int r, int c)
    {
        if (r < 0 || c < 0 || r >= g.Length || c >= g[0].Length || g[r][c] != '1') return;
        g[r][c] = '0';
        Sink(r + 1, c); Sink(r - 1, c); Sink(r, c + 1); Sink(r, c - 1);
    }
    for (int r = 0; r < g.Length; r++)
        for (int c = 0; c < g[0].Length; c++)
            if (g[r][c] == '1') { count++; Sink(r, c); }
    return count;
}

// Shortest path in an unweighted graph — BFS
static int ShortestPath(Dictionary<int, List<int>> graph, int from, int to)
{
    var dist = new Dictionary<int, int> { [from] = 0 };
    var q = new Queue<int>([from]);
    while (q.Count > 0)
    {
        var node = q.Dequeue();
        if (node == to) return dist[node];
        foreach (var next in graph.GetValueOrDefault(node, []))
            if (dist.TryAdd(next, dist[node] + 1)) q.Enqueue(next);
    }
    return -1;
}