Many distance queries on a small map
A map has n towns numbered 0 to n - 1. Each entry of roads is [a, b, km]: a two-way road of length km. Each entry of queries is [start, end]. Return a list with the length of the shortest route for each query, in order, or -1 when the two towns are not connected. A town is 0 km from itself.
There are at most 100 towns but there can be thousands of queries. Lengths are positive, no road joins a town to itself, and two towns may be joined by several roads.
Besides the tests, one large input (30 towns, 10,000 queries) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.
Examples
shortest_distances(4, [[0,1,4],[1,2,1],[0,2,7],[2,3,2]], [[0,2],[0,3],[3,1],[1,1]])→[5,7,3,0]shortest_distances(4, [[0,1,3],[2,3,5]], [[0,1],[1,2],[3,2]])→[3,-1,5]shortest_distances(2, [[0,1,9],[1,0,4]], [[1,0],[0,1]])→[4,4]