Graphs

 

Objectives

 

Definition and Terminology

Definition. A graph G=(V,E) consists of a set V of vertices and a set E of edges connecting vertices

Graph traversals

Problems with graph traversals:

Both of these problems can be taken care of by marking the nodes already visited and testing for this mark each time a nodes is about to be visited

 

Depth-first search (DFS)

 

Breadth-first search

 

Representing graphs

Adjacency matrix

Definition. For a graph G=(V,E) with n vertices (V={v1,v2,...,vn}) the adjacency matrix is an n by n matrix M defined over {0,1} such that M[i,j]=1 a if there is a vertex connecting vi and vj, and M[i,j]=0 otherwise.

 

Adjacency list

Definition. The adjacency list is an array of linked lists corresponding to each of the vertices of the graph. A list corresponding to a given vertex contains all the vertices adjacent to it.

 

Comparing representations

From the point of view of space requirement:

 

From the point of view of time requirement:

The graph ADT

Type: a set of graphs

Operations:

 

Graph problems

Topological sorting

The problem: given a directed acyclic graph order the vertices such that (vi,vj) is an edge, than vi precedes vj in the ordering

 

Shortest-path problems

  1. Single source shortest path

The problem: given a (weighted) graph G and a vertex in G, find the shortest paths from x to all the other vertices in G

Dijkstra's algorithm - at any time maintain the shortest distance estimate for each node

 

  1. All-pair shortest path

The problem: given a (weighted) graph, find the shortest distance between all pairs of vertices

Floyd's algorithm - keep the shortest k-path for all pairs

Minimum cost spanning tree

The problem: a minimum-cost spanning tree of a weighted graph G is a subgraph of G that contains all the vertices of G, is a tree, and has the sum of the weights minimal

  1. Prim's algorithm
  2. start from any vertex of the graph and add the lowest cost edge to the tree so far constructed till all the vertices had been added
  3. Prim's algorithm is a greedy algorithm

Theorem. Prim's algorithm produces a minimum-cost spanning tree

  1. Kruskal's algorithm
  2. maintains a set of subtrees and adds edges (combines equivalence classes) one at a time by selecting the shortest one
  3. edges can be processed in order of weight by storing them into a min-heap