Trains @ Königsberg

The above image represents a map of Königsberg. The green areas are land and the yellow lines are bridges.

The emperor of the kingdom wants to set up a train service that transports people from a landmass to another within the empire using the bridges.

There are people in the red castle who want to go to the blue castle subject to the following conditions:

  • The route cannot traverse a bridge twice.
  • The route can visit a landmass numerous times, including the land of the red castle.
  • The route stops the first time it reaches the blue castle.

How many possible train routes could they take?


The answer is 23.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

It is clear that we could reduce this into a multigraph as follows:

We want to ask, How many walks are there from the red node to the blue node that does not repeat edges?

Suppose ways(bridges, node, target) \text{ways(bridges, node, target)} is the number of ways one can reach the target from the current node using the bridges currently available. Then, at this point, we could use one of the bridges accessible to us right now and try to reach the target from that node.

ways(bridges, node, target) = i b r i d g e s [ n o d e ] ways(bridges \ { i } , node adjacent to i, target) \text{ways(bridges, node, target)} = \sum_{i \in bridges[node]} \text{ways(bridges} \backslash \left \{i \right \},\text{ node adjacent to i, target)}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def ways(edgelist, node, target):
    if node == target:
        return 1
    total = 0
    for e in edgelist:
        if node in e:
            copylist = [i for i in edgelist]
            copylist.remove(e)
            total += ways(copylist, sum(e)-node, target) #sum(e)-node just picks the adjacent node
    return total

Now, we can run this with:

1
2
edgelist = [(1, 2), (1, 2), (2, 3), (2, 3), (1, 4), (2, 4), (3, 4)]
print(dptrack(edgelist, 1, 3))

For a small number of bridges, this problem can be solved easily with recursion. As the number grows, we might need to resort to dynamic programming or memoization techniques.

It would be worth mentioning that you're unable to leave the blue side once reached.

Josh Stubbs - 4 years, 8 months ago

Log in to reply

Yes, thanks, I did that now.

Agnishom Chattopadhyay - 4 years, 8 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...