先看题目:https://ac.nowcoder.com/acm/problem/16708
题目描述:
小卒从(0,0)点出发,不能通过象的控制点,问小卒到达(n,m)的路径有几条?
解题思路:
dp[i][j]定义为从(0,0)到(i,j)的路径数,dp[i][j]=dp[i-1][j]+dp[i][j-1]
这题处理边界稍有点麻烦。编程实现的话用for循环就能解决。
结果可能会比较大,要开long long
代码:
#include<bits/stdc++.h> using namespace std; typedef long long ll; int n, m, x, y; ll dp[50][50]; int lab[50][50]; int dir[8][2]={-1,-2,1,-2,-2,-1,2,-1,-2,1,-1,2,1,2,2,1}; int main() { cin >> n >> m >> x >> y; dp[0][0] = 1; lab[x][y] = 1; for(int i = 0; i < 8; i++) { int xx = x+dir[i][0]; int yy = y+dir[i][1]; lab[xx][yy]=1; } for(int i = 0; i <= n; i++) for(int j = 0; j <= m; j++) { if(i == 0 && j == 0) continue; //容易漏 if(lab[i][j]) {dp[i][j] = 0; continue;} if(i == 0) {dp[i][j] = dp[i][j-1]; continue;} if(j == 0) {dp[i][j] = dp[i-1][j]; continue;} dp[i][j] = dp[i-1][j]+dp[i][j-1]; } printf("%lld\n",dp[n][m]); }