1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 6

CAP7004 · Unit 6: Graphs

Graph terminology and representations

8 practice questions

Key points

  • Sum of degrees = 2E for undirected graphs
  • Max edges n(n-1)/2
  • Adjacency list O(V+E) for sparse; matrix O(V^2) for dense
  • Undirected matrix is symmetric

A graph G = (V, E) has vertices and edges. Edges may be undirected or directed, and weighted or unweighted.

Terms: degree (edges at a vertex); in a directed graph in-degree and out-degree. A path is a vertex sequence joined by edges; a cycle returns to its start. A graph is connected if every vertex can reach every other; otherwise it has several components. A DAG is a directed acyclic graph. A tree is a connected graph with no cycles and V - 1 edges.

Counting: the sum of degrees = 2E in an undirected graph. A simple undirected graph on n vertices has at most n(n-1)/2 edges (10 for n = 5, 15 for n = 6).

Representations:

Adjacency listAdjacency matrix
SpaceO(V + E)O(V^2)
Is edge (u, v) present?O(degree)O(1)
List neighbours of uO(degree)O(V)
Best forSparse graphsDense graphs
G = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"],
     "D": ["B", "C", "E"], "E": ["D"]}   # 5 vertices, 5 edges

The matrix of an undirected graph is symmetric. In this example D has degree 3 and the list holds 10 entries (2E).

Exam pitfall: with a matrix, adding a vertex requires rebuilding an O(V^2) structure.

Try two questions

Question 1 · Tier 2, Understand

Checking whether edge (u, v) exists is O(1) in which representation?

  1. Adjacency list
  2. Edge list
  3. Adjacency matrix
  4. Incidence list
Show the answer

C. The matrix cell M[u][v] is read directly.

Question 2 · Tier 1, Recall

A connected graph with no cycles is called a:

  1. DAG
  2. Bipartite graph only
  3. Tree
  4. Complete graph
Show the answer

C. A tree has V - 1 edges and exactly one path between any two vertices.