go-graph-traversing icon indicating copy to clipboard operation
go-graph-traversing copied to clipboard

Graph DFS and BFS implementation in golang

go-graph-traversing

Graph DFS and BFS implementation in golang

Breadth First Search

breadth_first_traversal

Algorithm BFS(G, v)
    Q ← new empty FIFO queue
    Mark v as visited.
    Q.enqueue(v)
    while Q is not empty
        a ← Q.dequeue()
        // Perform some operation on a.
        for all unvisited neighbors x of a
            Mark x as visited.
            Q.enqueue(x)

BFS visualization

Depth First Search

dfs

Algorithm DFS(G, v)
    if v is already visited
        return        
    Mark v as visited.
    // Perform some operation on v.
    for all neighbors x of v
        DFS(G, x)

DFS visualization