Graph Theory37 sections · 1633 units
Open in Course

Game Routes - Implementation

The code

function countRoutes(n, edges):
    adj := array of lists, size n + 1
    indegree := array of size n + 1, initialized to 0
    ways := array of size n + 1, initialized to 0
    queue := empty queue
    topoOrder := empty list
    MOD := 1000000007

    for each edge (a, b) in edges:
        add b to adj[a]
        indegree[b] := indegree[b] + 1

    for i from 1 to n:
        if indegree[i] = 0 then
            push i to queue

    while queue is not empty:
        u := pop from queue
        add u to topoOrder
        for each v in adj[u]:
            indegree[v] := indegree[v] - 1
            if indegree[v] = 0 then
                push v to queue

    ways[1] := 1

    for each u in topoOrder:
        for each v in adj[u]:
            ways[v] := (ways[v] + ways[u]) mod MOD

    print ways[n]

This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.