
‘N’ = 4, ‘M’ = 6
Given ‘GRID’:
(Empty cells represent the character ‘O’)

The Ninja can reach the nearest service station by moving two cells south and then three cells east. So, the answer is ‘5’.
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.
Each test case’s first line contains two space-separated integers, ‘N’ and ‘M’, denoting the number of rows and columns in the ‘GRID’.
The next ‘N’ lines contain ‘M’ characters denoting the elements of the 'GRID'.
For every test case, return the length of the shortest path to a service station. If no such path is available, return -1;
You do not need to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N, M <= 100
Value in each element of ‘GRID’ = {‘N’, ‘S’, ‘O’, ‘X’}
Time limit: 1 second
Consider the given ‘GRID’ as an undirected graph where each cell represents a vertex, and if two free cells are adjacent, they are connected by an edge. Dijkstra’s algorithm is used for finding the shortest path between nodes in a weighted graph. As the given graph is unweighted, the path length is equal to the number of edges, so consider each edge’s weight to be ‘1’. Consider the cell with the ninja as the source node and break the algorithm when we reach a cell with a service station. There are ‘N x M’ vertices where each vertex is of the form ‘[r, c]’ (‘r’: row number, and ‘c’: column number). Below is an implementation of Dijkstra’s algorithm using priority queue(in this case: min-heap):
First find the presence of ninja:
Now apply Dijkstra’s algorithm to find the minimum cost path to reach the target:
Since the given grid can be considered as an unweighted graph, we can find the shortest path for each node in ‘O(E + V)’ = ‘O(M * N)’ time using a modified Breadth-first search algorithm. The shortest path length will be equivalent to the node’s level in the BFS traversal tree.
Proof of correctness: As we move level-wise in BFS, if a child node is not visited, it’s not reachable from any previous levels. Its shortest path will be equal to (parent node’s level + 1). Even if it’s reachable from any other node from the next levels, the corresponding path length will always be greater.
Following is a BFS implementation to solve this problem: