Introduce some basic concepts and algorithms about graph theory.
Basic Concept
A Graph is, in its simplest form, a collection of points joined together in pairs by lines. In the jargon of the field the points are referred to as vertices or nodes and the lines are referred to as edges.
Terms:
1) Vertex = Node = Point = Actor
2) Edge = Line
Representation
1. Adjacency Matrix
2. Adjacency List
3. Comparison
The adjacency matrix saves search time and the adjacency list saves space.
Traversal(Graph Search)
1. Depth First Search
1] Visit vertex v.
2] Choose an adjacency vertex to DFS.
3] Repeart step #1,2 until all vectices are visited.
1 | def DFS(v): |
2. Breadth First Search
1] Visit vertex v.
2] Visit all adjacency vertices of v, and put them in the queue Q.
3] Visit v_news in V_new.
4] For v_new in Q, repeat step #2,3 until queue is null.
1 | def BFS(v): |
Algorithm
1. Shortest Path Algorithm
1) Floyd
Floyd algorithm is used to calculate the shortest distance between two auxiliary vertices. The step is:
1] Initialize adjacency matrix and distances.
2] For vertex i, check whether exists vertex k to set up Dis(i,k) + Dis(k,j) < Dis(i,j). If so, update Dis(i,j) = Dis(i,k) + Dis(k,j).
3] Repeat 2] until all vertices have been went through.
1 |
|
2) Dijkstra
Dijkstra algorithm is used to calculate the shortest single source path.
The step is:
1] Initialize adjacency matrix and shortest distance array(between first vertex and others).
2] Initialize two sets U and V, represent shortest path vertex collection/remain vertex. First, add the first vertex to U. Others have been put to V.
3] Compare the distance between the first vertex and vertices belong to set V to find the shortest one. Then add corresponding vertex to U.
4] If dis[v] > dis[u] + e[u][v], update dis[v] = dis[u] + e[u][v].
5] Repeat 3] 4] until all vertices are added to U namely none nodes in V.
1 |
|
2. Minimum Spanning Trees
1) Prime
Prime solves the Minimum Spanning Tree problem of weight connected graph. The step is:
1] Initialize G = <V, E>, and set U contains vertices of MST. So (V-U) includes other vertices. And set T stores edges of MST. First add a random vertex u to U.
2] Choose a vertex u of U and sort the distances between u and other alters. Choose the shortest one (u, v). Add v to U and add (u, v) to T.
3] Repeat 2] until U = V.
1 |
|
2) Kruskal
Do the same thing as Prime.
1] Sort all the edges in non-decreasing order of their weight.
2] Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it.
3] Repeat step#2 until there are (V-1) edges in the spanning tree.
1 |
|