Pascal's Travels HDU

来源:互联网 发布:mac chrome flash 发热 编辑:程序博客网 时间:2024/06/06 07:14

                         Pascal's Travels

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 2^63 paths for any board. 
Sample Input
423311213123131104333212131232212051110101111111111110111101-1
Sample Output
307
题意:有n行n列数据 ,从(1,1)点出发,每次只向右或向下走,每次走的距离就是所在点的数值,到(n ,n)的共有几种走法。

思路 :有的点可以走的到,有的点永远也到不了,可以用另一个dp数组存到对应点的走法。

首先dp数组清零,并且把起点位置dp[0][0]=1;并开始搜索,

两层for循环经过所有的点,能到达的点的dp值都大于零,从一个点到另一个点,要把这个点的dp值加给到达的那个点的dp值上,注意:(n,n)这个点不要搜了,因为不需要再往下走了。


#include<stdio.h>#include<string.h>long long int dp[60][60];int map[50][50];int main(){    int n;    while(~scanf("%d",&n)&&n!=-1)    {        int i,j,k;        memset(dp,0,sizeof(dp));        for(i=0; i<n; i++)            for(j=0; j<n; j++)                scanf("%1d",&map[i][j]);        dp[0][0]=1;        for(i=0; i<n; i++)            for(j=0; j<n; j++)                if(i==n-1&&j==n-1)                    continue;                else  if(dp[i][j])                {                    dp[map[i][j]+i][j]+=dp[i][j];                    dp[i][map[i][j]+j]+=dp[i][j];                }        printf("%lld\n",dp[n-1][n-1]);    }    return 0;}



原创粉丝点击