Straightest path

4.4

28 votes
Algorithms, Dijkstra's algorithm, Easy, Grammar-Verified, Graphs, Shortest Path Algorithm
Problem

You are playing a game on a grid of size N×M. The game has the following rules:

  • The grid contains cells that the player can move to. These are denoted by a period (.)
  • The grid contains cells that the player cannot move to. These are denoted by an asterisk (*)
  • The player starts on the cell marked with a V.
  • The player has to reach the cell marked with an H.

Write a program to find the path which has the minimum number of changes in direction. Print the number of times that the player needs to turn on the path

Input format

  • First line: N and M
  • Next N lines: M characters (denoting the cells of the grid)

Output format

Print the minimum number of times that the player needs to turn on the required path. If no path exists, print -1.

Constraints

1N,M103

Sample Input
5 4
V...
***.
....
.***
.H.*
Sample Output
4
Time Limit: 4
Memory Limit: 256
Source Limit:
Explanation

For the given sample case, Wizard will take first turn at cell (1,4) , second turn at cell (3,4) ,third turn at cell (3,1), and fourth turn at cell (5,1).

Editor Image

?