Bronze Lilypad Pond

Time limit1sMemory limit128 MB

Summary
Find the minimum number of generalized knight's moves to get from the start lilypad to the destination on a grid, where only landing cells must be lilypads.
Level

Medium4 of 10

Topics
BFS, Graph, Implementation
Solved
No attempts yet

Problem

Farmer John built a rectangular pond for his cows to admire and exercise in. The pond is divided into a grid of MM rows and NN columns (1≤M≤301 \le M \le 30, 1≤N≤301 \le N \le 30). Every cell holds one of three things: a remarkably sturdy lilypad, a rock, or open water.

Bessie the cow is practising her ballet by leaping from lilypad to lilypad. She currently stands on one lilypad and wants to reach another. She may land only on lilypads — never on open water and never on a rock.

Each of Bessie's leaps has the shape of a generalized knight's move: she travels M1M_1 cells in one cardinal direction and then M2M_2 cells in a perpendicular direction, or M2M_2 cells in one direction and then M1M_1 cells in a perpendicular direction (1≤M1≤301 \le M_1 \le 30, 1≤M2≤301 \le M_2 \le 30, M1≠M2M_1 \ne M_2). This gives up to eight possible landing cells per leap. Only the landing cell must be a lilypad; Bessie may fly over water and rocks freely.

Given the pond layout and the two jump lengths, determine the minimum number of leaps Bessie needs to travel from her starting lilypad to her destination lilypad. A route is guaranteed to exist for every input.

Input

The first line contains four space-separated integers MM, NN, M1M_1, and M2M_2.

Each of the next MM lines contains NN space-separated integers describing one row of the pond, using these codes:

  • 00 — open water
  • 11 — a lilypad
  • 22 — a rock
  • 33 — the lilypad Bessie starts on
  • 44 — the lilypad that is Bessie's destination

Exactly one cell equals 33 and exactly one cell equals 44.

Output

Print a single integer: the minimum number of leaps Bessie must make to reach her destination lilypad from her starting lilypad.

Hint

Think of each lilypad as a node in a graph, with an edge between two lilypads whenever a single generalized knight's move connects them. A breadth-first search from the starting lilypad then yields the minimum number of leaps. Remember that Bessie may pass over water and rocks — only the landing cell must be a lilypad.

Examples2

  1. Example 1

    Input
    4 5 1 2
    1 0 1 0 1
    3 0 2 0 4
    0 1 2 0 0
    0 0 0 1 0
    
    Expected output
    2
    
  2. Example 2

    Input
    3 3 1 2
    3 0 0
    0 0 4
    0 0 0
    
    Expected output
    1