Domanda di colloquio di Amazon

Write algorithm/code to find longest path between any two cities. 4X4 matrix was given. If there is no connectivity between two cities then the distance between them was given as -1. Its cyclic graph.

Risposta di colloquio

Anonimo

15 giu 2011

Finding longest path between two nodes in a graph is an NP Hard problem. So, we should not try to find a polynomial solution to this problem. As you can see the given problem is of very small size. So even brute force is acceptable. Solution: Let there be n cities. GIven starting city as S and destination city as D. We are left with n-2 cities. There are approximately 2^(n-2) * (n-2)! ways for reaching D from S. Find length of all these ways and choose the smallest one.

4