Graphs

Terminology

node

A point or vertice on the graph. (Also stated as V)

edge

The connection between two nodes. (Also stated as E)

connected

When every node has a path to another node.

cycle

When you start at NodeXNode_X, follow the links, and end back at NodeXNode_X. (Can't be only 2 nodes)

acyclic

A graph that contains no cycles.

directed

When there is a direction to the connections. (This helps making asymetric connections, Ex.: A10BA \rightarrow_{10} B but B20AB \rightarrow_{20} A)

undirected

Not directed. (The default) (Ex.: ABA \rightarrow B has the same weight as BA)B \rightarrow A)

weighted

The edges have a weight associated with them.

dag

Directed, acyclic graph.

Representing Graphs

Adjacent List

A list, where each main index of the list points to a node of the graph, describing its connections to the other nodes.

This representation is more commonly used.

Drawing

Traversing/Searching with BFS

Traversing/Searching with DFS

Easier to preserve the path.

Runs on O(V+E)O(V+E).

Adjacent Matrix

A matrix, where each main index of the first array points to a node of the graph, describing in a second array the weights to the other nodes or zero if there is no connection.

Drawing

Traversing/Searching with BFS

Dijkstra's Shortest Path

An algorithm to find shortest path, meaning find the edge connections with smallest weight.

Don't use negative weight.

Drawing

Array Solution

This algorithm will run on O(V2+E)O(V² + E) because of the way it uses to get the next lowest unseen node.

seen array has size V, and the while loop will run for each node on the graph in worst case, making it VVV*V.

The way this specific algorithm works is

  1. Will start from the source node (Ex.: Node 0), and check how much it costs to go to each of the unseen neighbors (Node 1 and Node 2).

    1. After this check it will save:

      1. In weights how much it costs to get to Node 1 = 1 and Node 2 = 5.

      2. In path it will have that the best way yet to get to Node 1 and Node 2 is from Node 0.

  2. Then it will check the next unseen node that has the lowest weight in weights. (So it will try to stay on the best path). In this example it will check now Node 1, and its unseen neighbors.

    1. After the check:

      1. In weights it will have that to get to Node 2 = 7 and Node 3 = 1. But we already know that there is a better path for Node 2 which is from Node 0, so reaching Node 2 from Node 1 is ignored.

      2. In path we have now that reaching Node 1 & 2 should be from Node 0 and reaching Node 3 should be from Node 1.

  3. Step 2 is repeated until there are no more unseen nodes. The algorithm will prioritize paths with lowest weight and will override them if a better one is found.

  4. At the end it just reconstruct the path to return it.

Heap Solution

Last updated