
1 - Which means you can go from (i, j)-th cell to the (i, j+1)-th cell.
2 - Which means you can go from (i, j)-th cell to the (i, j-1)-th cell.
3 - Which means you can go from (i, j)-th cell to the (i+1, j)-th cell.
4 - Which means you can go from (i, j)-th cell to the (i-1, j)-th cell.
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first input line of each test case contains two integers ‘N’ and ‘M’ denoting the number of rows and columns in the grid, respectively.
Each of the next ‘N’ lines contains ‘M’ space-separated integers denoting the cell values of the grid.
For each test case, return the minimum cost to make at least one valid path in the grid.
Print the output of each test case in a separate line.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 50
1 <= N <= 100
1 <= M <= 100
Time limit: 1 sec
The basic idea of this approach is to model this problem as a graph problem. Let us create a directed weighted graph with cells of the given grid as vertices. There will be an edge of weight 0 if we can move from (i, j)-th cell to neighbouring cells (i, j+1), (i, j-1), (i+1, j) following the sign of (i, j)-th cell, otherwise the weight of the edge will be 1.
The figure below shows the graph constructed for the first test case of sample test case 1. Edges of weight 0 are denoted in red colour and whereas black edges are of weight 1.
We can observe that the problem finally boils down to finding the single source shortest path in a directed weighted graph. We can use the Dijkstra algorithm to do this task. You can refer to this tutorial of cp-algorithms for a more detailed explanation of the Dijkstra algorithm. https://cp-algorithms.com/graph/dijkstra_sparse.html
We will be using a min-heap based implementation of the Dijkstra algorithm. Now consider the following steps :