Data Structures & AlgorithmsVery hardICPC regional · matrix power on graphs

Problem: A directed graph has edges 0->1, 0->2, 1->2, 1->3, 2->3. Let A be its adjacency matrix. How many walks of exactly 3 edges go from vertex 0 to vertex 3? Use the code below.

Problem: A directed graph has edges 0->1, 0->2, 1->2, 1->3, 2->3. Let A be its adjacency matrix. How many walks of exactly 3 edges go from vertex 0 to vertex 3? Use the code below.
A = [[0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0]]
def mul(X, Y):
    return [[sum(X[i][k] * Y[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
P = A
for _ in range(2):
    P = mul(P, A)
print(P[0][3])
What is printed?
  1. A. 2
  2. B. 0
  3. C. 3
  4. D. 1

Correct answer: D. 1

The only 3-edge walk is 0 to 1 to 2 to 3. The two-edge walks 0-1-3 and 0-2-3 end at 3 too early, so the matrix power A^3 gives 1.

More Coding Interview Problems questions

Exams that ask this topic