View on GitHub

reading-notes

CodeFellows Class Reading Notes

Graphs

Graph: a non-linear data structure that can be looked at as a collection of vertices (or nodes) potentially connected by line segments named edges.

Terms:


Types of Graphs:

Directed vs Undirected

Undirected: a graph where each edge is undirected or bi-directional. This type of graph does not move in any direction

Directed (Digraph): a graph where every edge is directed. This type of graph has direction, as each node is directed at another node with a specific requirement of what node should be referenced next (like a linked list)

Complete vs Connected vs Disconnected

Complete: all nodes are connected to all other nodes

Connected: all vertices/nodes have at least one edge

Disconnected: some vertices may not have edges. Stand alone nodes may exist

Acyclic vs Cyclic

Acyclic: a directed graph without cycles

Cyclic: a directed graph with cycles


Representation

Adjacency Matrix: 2-dimensional array of size nxn, where n = the number of vertices in the graph.

Adjacency List: a collection of linked lists or array that lists all other vertices that are connected.


Weighted Graphs


Traversals

Breadth First:

Steps of Traversal:

  1. Enqueue the declared start node into a Queue
  2. Create a loop that will continue while there are nodes present in the queue
  3. Dequeue the first node in the queue
  4. If the dequeued node had unvisited child nodes, mark the unvisited children as visited and then re-insert them into the queue

Pseudocode:

ALGORITHM BreadthFirst(vertex)
    DECLARE nodes <-- new List()
    DECLARE breadth <-- new Queue()
    breadth.Enqueue(vertex)

    while (breadth is not empty)
        DECLARE front <-- breadth.Dequeue()
        nodes.Add(front)

        for each child in front.Children
            if(child is not visited)
                child.Visited <-- true
                breadth.Enqueue(child)   

    return nodes;

Depth First:

Steps of Traversal:

  1. Push root node into the stack
  2. Start a while loop that will continue while the stack is not empty
  3. Peek at the top node in the stack
    • If the top node has unvisited children, mark the top node as visited and then push any unvisited children back into the stack
    • If the top node does not have unvisited children, Pop that node off the stack

Use Cases


Home