

1. Cities are numbered from [0, 1, 2 ….. N-1] in input data.
2. To minimize the cost for a pair (i, j), any road can be travelled any number of times.
3. For any pair (i, j), if city 'j' is not reachable from city 'i', the value of matrix[i][j] should be '-1'.
4. If matrix[i][j] is negative for any pair, you should minimize it too, i.e., find the most negative value.
5. For any pair (i, j), if 'j' is reachable from city 'i', but it’s impossible to minimize the cost, fill the entire answer matrix with integer '-1'.
The first line contains 'T', denoting the number of tests.
For each Test :
The first line contains two space-separated integers, 'N' and 'M', denoting the number of cities and roads, respectively.
Next 'M' lines contain three integers 'x[i]', 'y[i]', 'w[i]' denoting there is a directed road from city 'x[i]' to city 'y[i]', and having tax 'w[i]'.
For each Test :
There should be 'N' lines, each containing 'N' space-separated integers. The j-th value in i-th row denotes the minimum tax to travel from city 'i' to city 'j'.
If a pair of cities is unreachable, print integer -1.
If a pair is reachable but cannot minimize cost, all elements in the matrix must be -1.
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= 'T' <= 10
1 <= 'N' <= 10^3
0 <= 'M' <= min(10^3 , N*(N-1)/2 )
0 <= x[i], y[i] < 'N' i ∈ (1,M)
-10^4 <= w[i] <= 10^4 i ∈ (1, M)
Note - Sum of 'N' and Sum of 'M' over all test cases does not exceed 10^3.
Time Limit: 1 sec
Our task is to find the shortest path between each pair of vertices, for which Johnson’s algorithm is an optimal solution.
Let's understand how Johnson's algorithm works.
There exist two standard algorithms, Dijkstra and Bellman-ford, to find the shortest path from a fixed source vertex. For both algorithms, time complexities are O(E logV) and O(VE), respectively, where 'V' and 'E' are the numbers of vertices and edges.
If we run the Dijkstra algorithm from each vertex, the shortest paths for all pairs can be calculated in O(VE logV) time, but the problem is that it doesn't work for a graph with negatively weighted edges.
The main idea of Johnson's algorithm is to re-weight all the edges to make them positive, apply the Dijkstra algorithm on each vertex as a source node, and finally convert the weights back to their original value.
To calculate the new weights of edges, the Bellman-ford algorithm is used. Here, a dummy node is introduced in the graph, and it has an outgoing edge (zero weighted) to each vertex of the graph. The minimum distance to each vertex from this dummy is calculated in O(VE) time. Let these distances be H[0, 1, 2 ….. V-1].
Updated weight of an edge (i, j) will be (original_weight + H[i] - H[j] ). It’s guaranteed that all the edge weights become non-negative.
Using Dijkstra, assume the cost of a path (x, y) is ‘C’ then the original cost will be (C + H[y] - H[x]).
Algorithm: