Problem
This problem is asked at so: I have a network of stations in a subway system. The number of stations, the number of tickets I can travel between stations with, and which stations are connected to each other are given in a text file as input to the program. Which stations are connected to each other are kept in a 2D boolean matrix. I have to find the number of paths from station 0 and back to 0 that uses all of the tickets.
OR
Given a graph (as an adjacency matrix), count the number of roundtrip paths of exactly k steps that start and end at the origin node (node 0).
Examples
Example 1
graph TD; A(0) --- B(1) & E(4) B --- F(5) & C(2) & G(6) F --- D(3) C --- D G --- D E --- D
Adjacency matrix of the graph:
$$ \begin{array}{|c|ccccccc|} \hline & 0 & 1 & 2 & 3 & 4 & 5 & 6 \\ \hline 0 & 0 & 1 & 0 & 0 & 1 & 0 & 0 \\ 1 & 1 & 0 & 1 & 0 & 0 & 1 & 1 \\ 2 & 0 & 1 & 0 & 1 & 0 & 0 & 0 \\ 3 & 0 & 0 & 1 & 0 & 1 & 1 & 1 \\ 4 & 1 & 0 & 0 & 1 & 0 & 0 & 0 \\ 5 & 0 & 1 & 0 & 1 & 0 & 0 & 0 \\ 6 & 0 & 1 & 0 & 1 & 0 & 0 & 0 \\ \hline \end{array} $$
|
|
Solution
Method 1 – Top-Down Dynamic Programming (Memoized Recursion)
Intuition
Use recursion with memoization to count the number of ways to return to node 0 in exactly k steps. At each step, try all possible next nodes, and cache results to avoid recomputation.
Approach
- Define a function
f(u, t)
= number of ways to reach node 0 from node u in t steps. - Base case: if
t == 0
, return 1 ifu == 0
, else 0. - For each neighbor v of u, recursively compute
f(v, t-1)
and sum the results. - Use memoization to cache results for
(u, t)
. - The answer is
f(0, k)
.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(kN^2)
, where k is the number of steps and N is the number of nodes. Each state(u, t)
is computed once, and for each, we try allN
neighbors. - 🧺 Space complexity:
O(kN)
, for the memoization table.
Method 2 – Bottom-Up Dynamic Programming
Intuition
Use dynamic programming to count the number of ways to reach each node in exactly t steps, building up from 0 to k steps. The answer is the number of ways to return to the origin node in k steps.
Approach
- Let
dp[t][u]
be the number of ways to reach node u in t steps. - Initialize
dp[0][0] = 1
(start at node 0 with 0 steps). - For each step t from 1 to k:
- For each node s, if
dp[t-1][s] > 0
, for each neighbor adj of s:- Add
dp[t-1][s]
todp[t][adj]
if there is an edge from s to adj.
- Add
- The answer is
dp[k][0]
(number of ways to return to node 0 in k steps).
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(kN^2)
, where k is the number of steps and N is the number of nodes. Each step considers all pairs of nodes. - 🧺 Space complexity:
O(kN)
, for the DP table.