Palindromic Paths
Time limit1sMemory limit256 MB
Count distinct palindromic strings spelled by right-down paths from the top-left to the bottom-right of an N by N letter grid.
Problem
Farmer John's farm is an grid of fields (), and every field carries one uppercase letter from A to Z.
Every day the cow Bessie walks from the field in the upper left corner to the field in the lower right corner. Each step moves her one field to the right or one field down. She reads the letters of the fields she visits, the first and the last one included, so one walk spells a string of length .
Bessie gets disoriented when that string is a palindrome. A palindrome reads the same forward and backward, so she loses track of the direction she walked.
Count the palindromes Bessie can spell. Two walks that spell the same palindrome count once.
Take this grid.
ABCD
BXZX
CDXB
WCBA
Several walks spell ABXZXBA, and Bessie can spell exactly four palindromes: ABCDCBA, ABCWCBA, ABXZXBA, ABXDXBA.
Input
The first line contains . Each of the next lines contains one row of the grid as characters in the range A to Z.
Output
Print the number of distinct palindromes Bessie can spell.