home page -> teaching -> graph algorithms -> methods of representing a graph

Graph algorithms - seminary - methods of representing a graph

Exercices

  1. Create a python representation based on a collection of outbound neighbours for each vertex
  2. Interface: given a graph g and a vertex x, it should allow to do for y in g.parseNOut(x)
  3. Choices: vertices are numbers from 0 to n-1 or they are arbitrary hashables; the graph is created with no vertices and the vertices are added one by one, vs the graph is created by giving the number of vertices or the collection of vertices.
  4. Make a main program that creates a small graph and then it parses the vertices and prints all neighbours for each vertex:
        for x in g.parseX(): # this parses all vertices
            line = str(x) + " :"
            for y in g.parseNOut(x):
                line = line + " " + str(y)
            print(line)
      
  5. Create a random graph with n vertices and m edges; make the main program parse the outbound neighbours of all vertices and the inbound neighbours of all vertices, but without printing (just masure the time needed).
  6. Compare the time needed for the previous operation for:

Some theory

Graph representation:

Adjacency matrix
Ai,j = true iff there is an edge from i to j
List of neighbours for each vertex
The graph is represented as a list or dictionary, with one entry for each vertex, and where values are the list or the set of (outbound) neighbours or edges from the current vertex.
Double list of neighbours for each vertex
As above, but for each vertex, we have two lists or sets: one for inbound edges, and one for outbound edges.

Order of magnitude for real-world problems:

Sample implementation: graph.py

Radu-Lucian LUPŞA
2020-03-12