A park in Logic City is an N×N grid of squares (2≤N≤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) to the bottom right square (N,N).