Graphs - JamesDansie/data-structures-and-algorithms GitHub Wiki

Graphs

Author: James Dansie

Graphs are similar to nodes and linked lists in that they have nodes, but the nodes can have many different relations. In some graphs all the nodes connect to each other. In other graphs only some nodes connect to others. Some graphs can only have one way connections, and others can connect both ways.

The types of traversals are; breadth first, and depth first. Breadth first adds the nodes to a queue, and then runs while the queue is not empty. A depth first does the same thing, but with a stack. Sample pseudo code for breadth first;

public List<Node> BreadthFirst(Node root)
{
    List<Node> order = new List<Node>();
    Queue<Node> breadth = new Queue<Node>();
    breadth.Enqueue(root);

    while (breadth.TryPeek(out root))
    {
        Node front = breadth.Dequeue();
        order.Add(front);

        foreach (Node child in front.Children)
        {
            if(!child.Visited)
            {
                child.Visited = true;
                breadth.Enqueue(child);
            }
        }
    }

    return order;
}

Referenes

⚠️ **GitHub.com Fallback** ⚠️