Pascal's Travels
InterviewTime limit1sMemory limit128 MB
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 board. Each square holds a single nonnegative digit from to .
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 you may move either squares to the right or 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 is a dead end, because a step of length makes no progress.
Count how many distinct paths lead from the top-left square to the bottom-right square.
Input
The input describes between and boards and ends with a line containing only .
Each board begins with a line containing a single integer (), the number of rows (and columns) of the board. The next lines each contain digits (each from to ) 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 .
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++).