Under construction

Still being built. Things may change

The Chivalrous Cow

Interview

Time limit1sMemory limit128 MB

Summary
Find the fewest knight-move jumps on an X by Y grid with obstacles to get from the start square to the hay bale.
Level

Medium4 of 10

Topics
BFS, Graph, Array, Shortest path
Solved
No attempts yet

Problem

Farmer John traded one of his cows for a cow called "The Knight." This cow jumps around the pasture exactly like a knight on a chessboard: each jump moves two squares in one direction and one square in the perpendicular direction (an "L" shape). The Knight cannot land on an obstacle, but she can freely hop across the pasture, which is divided into an X×YX \times Y grid of squares (1≤X≤1501 \le X \le 150, 1≤Y≤1501 \le Y \le 150).

The Knight loves hay. Given a map showing her starting square, the obstacles, and the hay bale, determine the minimum number of jumps she needs to reach the hay. On the map, the Knight's starting square is marked K, every obstacle is marked *, and the hay bale is marked H; empty squares are ..

A typical map looks like this (row and column numbers are shown only as a guide):

11 | . . . . . . . . . .
10 | . . . . * . . . . .
 9 | . . . . . . . . . .
 8 | . . . * . * . . . .
 7 | . . . . . . . * . .
 6 | . . * . . * . . . H
 5 | * . . . . . . . . .
 4 | . . . * . . . * . .
 3 | . K . . . . . . . .
 2 | . . . * . . . . . *
 1 | . . * . . . . * . .
 0 ----------------------
                       1
   0 1 2 3 4 5 6 7 8 9 0

In this map, the Knight can reach the hay bale H from her starting square K in as few as 5 jumps (other routes of length 5 may also exist). It is guaranteed that the hay bale can always be reached.

Input

  • The first line contains two space-separated integers XX and YY.
  • Each of the next YY lines contains exactly XX characters with no spaces, giving the map one row at a time from the top row to the bottom row. Each character is . (empty), * (obstacle), K (the Knight's start), or H (the hay bale). There is exactly one K and exactly one H.

Output

  • Print a single integer: the minimum number of jumps the Knight needs to reach the hay bale. It is always possible to reach the hay bale.

Examples3

  1. Example 1

    Input
    10 11
    ..........
    ....*.....
    ..........
    ...*.*....
    .......*..
    ..*..*...H
    *.........
    ...*...*..
    .K........
    ...*.....*
    ..*....*..
    
    Expected output
    5
    
  2. Example 2

    Input
    3 3
    K..
    ...
    .H.
    
    Expected output
    1
    
  3. Example 3

    Input
    5 5
    K....
    .....
    .....
    .....
    ....H
    
    Expected output
    4