Pascal's Travels

Interview

Time limit1sMemory limit128 MB

Summary
Count paths on an n by n digit board from top-left to bottom-right, where each square's digit sets the exact right or down step length.
Level

Medium4 of 10

Topics
Dynamic programming, Array, Implementation, Graph
Solved
No attempts yet

Problem

You are given an n×nn \times n board. Each square holds a single nonnegative digit from 00 to 99.

You start on the top-left square and want to reach the bottom-right square. The digit written on the square you are currently on is the exact length of your next step: from a square holding the value dd you may move either dd squares to the right or dd squares down. A move that would leave the board is not allowed, and every move must go to the right or down. A square containing 00 is a dead end, because a step of length 00 makes no progress.

Count how many distinct paths lead from the top-left square to the bottom-right square.

Input

The input describes between 11 and 3030 boards and ends with a line containing only −1-1.

Each board begins with a line containing a single integer nn (4≤n≤344 \le n \le 34), the number of rows (and columns) of the board. The next nn lines each contain nn digits (each from 00 to 99) with no spaces between them.

Output

For each board, print a single line containing one integer: the number of distinct paths from the top-left square to the bottom-right square. For every board this count is smaller than 2632^{63}.

Hint

Examining every path by brute force will likely exceed the time limit, so use dynamic programming instead. Every answer fits in a signed 64-bit integer (for example, long in Java or long long in C/C++).

Examples2

  1. Example 1

    Input
    4
    2331
    1213
    1231
    3110
    4
    3332
    1213
    1232
    2120
    5
    11101
    01111
    11111
    11101
    11101
    -1
    
    Expected output
    3
    0
    7
    
  2. Example 2

    Input
    4
    1111
    1111
    1111
    1111
    -1
    
    Expected output
    20