Consistent Letter Path

Find the shortest path on an N by N letter grid from top-left to bottom-right where no letter appears in both lowercase and uppercase along the path.

Medium6BFSBit manipulationGraphShortest pathInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

A park in Logic City is an N×NN \times N grid of squares (2N1002 \le N \le 100). Every square holds one of the first ten letters of the alphabet, abcdefghij, written in either lower case or upper case. The people of Logic City cross a park only along a consistent path. Once they have stepped on a square marked with a lower case c, they will not step on a square marked with an upper case C later on.

A consistent path is a sequence of squares that meets two conditions.

  • Consecutive squares in the sequence share an edge, so every move goes up, down, left, or right.
  • No letter appears in the sequence in both cases. Each letter is either absent from the sequence, or present only in lower case, or present only in upper case.

The length of a path is the number of squares in the sequence, counting the first and the last square.

In the picture below, the left grid is a park and the right grid marks one consistent path of length 13 in that park. Squares on the path keep their letter and the other squares are replaced by dots.

DdaAaA D.....
CBAcca C.....
eEaeeE e.....
bBbabB b.bab.
DbDdDc DbD.D.
fFaAaC ....aC

Compute the length of a shortest consistent path from the top left square (1,1)(1, 1) to the bottom right square (N,N)(N, N).

Input

The first line contains the size of the park, NN (2N1002 \le N \le 100). Each of the next NN lines contains a string of length NN. The jj-th letter of the ii-th string is the letter written on square (i,j)(i, j), and it is one of abcdefghij and ABCDEFGHIJ.

Output

Print one line with the length of a shortest consistent path from (1,1)(1, 1) to (N,N)(N, N). If no consistent path exists, print -1.