Total Submissions: 3554 |
| Accepted: 1502 |
Description
An
n x n game board is populated with integers, one nonnegative integer
per square. The goal is to travel along any legitimate path from the
upper left corner to the lower right corner of the board. The integer
in any one square dictates how large a step away from that location
must be. If the step size would advance travel off the game board, then
a step in that particular direction is forbidden. All steps must be
either to the right or toward the bottom. Note that a 0 is a dead end
which prevents any further progress.
Consider the 4 x 4 board shown in Figure 1, where the solid circle
identifies the start position and the dashed circle identifies the
target. Figure 2 shows the three paths from the start to the target,
with the irrelevant numbers in each removed.
| |
Figure 1
| Figure 2
|
Input
The
input contains data for one to thirty boards, followed by a final line
containing only the integer -1. The data for a board starts with a line
containing a single positive integer n, 4 <= n <= 34, which is
the number of rows in this board. This is followed by n rows of data.
Each row contains n single digits, 0-9, with no spaces between them.
Output
The
output consists of one line for each board, containing a single
integer, which is the number of paths from the upper left corner to the
lower right corner. There will be fewer than 263 paths for any board.
Sample Input
4
2331
1213
1231
3110
4
3332
1213
1232
2120
5
11101
01111
11111
11101
11101
-1
Sample Output
3
0
7
Hint
Brute
force methods examining every path will likely exceed the allotted time
limit. 64-bit integer values are available as long values in Java or
long long values using the contest's C/C++ compilers.
解答:
一道很简单的备忘录dp,最开始想搜索来着,一经仔细思考发现是个dp问题。
思路:从左到右,从上至下,依次计算当前节点(q)可以step到哪里(记为p),在p的原值基础上加上当前节点q的所有到达路径数。最后在矩阵右下的终点里就记录了最终的路径数
注意:结果是long long int。
#include
#include
int board[50][50];
long long count[50][50];
char string[50];
void input(int size);
long long get_path(int size);
int main(int argc, char *argv[])
{
int n, i;
while (scanf("%d", &n) && n != -1)
{
memset(count, 0, sizeof(count));
count[0][0] = 1;
input(n);
printf("%lld\n", get_path(n));
}
}
void input(int size)
{
int i, j;
char *ch;
for (i=0 ; i {
scanf("%s", string);
ch = &string[0];
for (j=0 ; j {
board[i][j] = *ch - '0';
ch++;
}
}
}
long long get_path(int size)
{
int i, j, step;
for (i=0 ; i {
for (j=0 ; j {
step = board[i][j];
if (0 == step)
{
continue;
}
count[i + step][j] += count[i][j];
count[i][j + step] += count[i][j];
}
}
return count[size-1][size-1];
}
阅读(847) | 评论(0) | 转发(0) |