Stepping down the pond stones

An N × N grid of stones: stone (r, c) has a height and a colour. You start on any stone in the top row and want to reach any stone in the bottom row. In one jump you move to a neighbouring stone (up, down, left or right) that is strictly lower and of a different colour. Print the fewest jumps needed, or -1 if the bottom row cannot be reached.

Reported in: Infosys (SP / DSE · 22 Nov 2026) (memory-based)

Input

First line: N. Next N lines: the heights. Next N lines: the colours.

Output

The fewest jumps, or -1.

Constraints

1 ≤ N ≤ 500; heights and colours are integers up to 10^9.

Example 1

Input:
3
9 8 7
6 5 4
3 2 1
1 2 1
2 1 2
1 2 1

Output:
2

Example 2

Input:
2
5 5
5 5
1 2
2 1

Output:
-1

Example 3

Input:
3
9 1 9
8 9 9
7 9 9
1 1 1
2 1 1
1 1 1

Output:
2

Hint: All jumps cost the same, so this is a shortest path by breadth-first search. Start the search from every top-row stone at once and only follow jumps that go strictly lower onto a different colour.

All coding practice