cswork / OAOpen practice workspace

Capital OneOA #11

Labyrinth Right-Then-Down with Teleports

Estimated MediumJudge-ready

Topics (AI-labelled)SimulationHashing

Starting from the top-left corner, prefer moving right; move down only when the cell to the right is not walkable. When you step on a teleport start, teleport immediately and continue.

Input

n m; the number of obstacles b and b lines of 0-based coordinates; the number of teleports k and k lines of sr sc er ec. Teleport starts are unique, an end is never a start, and no teleport endpoint is an obstacle. This site adds: n,m≤100.

Output

If the bottom-right corner is reached, output the number of cells passed through (the start, teleport starts, and teleport ends all count); if there is no path, output -1; if revisiting a cell causes an infinite loop, output -2.

Example 1

Input:

3 4
1
0 1
1
1 1 2 2

Output:

5

Example 2

Input:

3 3
2
0 1
1 0
0

Output:

-1

Example 3

Input:

3 3
0
2
0 1 1 0
1 1 0 1

Output:

-2

Editorial

Loading solution…