Walks on a graph
Graph Walks
An undirected graph has vertices 1,2,3,4 and exactly these edges: 1–2, 2–3, 3–4, 4–1 and 1–3. A walk may revisit vertices and edges, including immediately backtracking. How many distinct walks of exactly 5 edges start at vertex 1 and finish at vertex 4? Distinguish walks by their entire ordered vertex sequences. There is exactly one one-edge walk from 1 to 4. Submit one integer.
2 ───── 3 │ ╱│ │ ╱ │ │ ╱ │ 1 ───── 4
Learning goal: Count walks of a fixed length using repeated neighbour totals.
Look for the underlying structure rather than guessing the next number. Submit only the final integer; you can open hints below as needed.
Check your answer without signing in. Sign in to save your progress.
Hints
Hint 1
Track the number of walks ending at each vertex after each step.
Hint 2
To find the next count at a vertex, add the prior counts of all its neighbours.
Hint 3
Starting from [1,0,0,0], repeat the adjacency update five times and read the count at vertex 4.
Common mistake to avoid
Counting only simple paths and incorrectly forbidding revisits.
How to approach this problem
Maintain a vector of counts at each vertex for each step. To compute the next vector, sum the previous counts from neighboring vertices, including backtracking.
Worked example with different values
On a path A–B–C starting at A, after two steps the counts at A and C are both 1, and B has count 0.
Apply the same reasoning to the challenge. This example is a separate practice problem.
Learn the technique: Sequence patterns: differences, recurrences and interleaving