【问题描述】
在平面上有一些二维的点阵。 这些点的编号就像二维数组的编号一样,从上到下依次为第 1 至第 n 行, 从左到右依次为第 1 至第 m 列,每一个点可以用行号和列号来表示。 现在有个人站在第 1 行第 1 列,要走到第 n 行第 m 列。只能向右或者向下 走。 注意,如果行号和列数都是偶数,不能走入这一格中。 问有多少种方案。
【输入格式】
输入一行包含两个整数 n, m。
【输出格式】
输出一个整数,表示答案。
【样例输入】
3 4
【样例输出】
2
【样例输入】
6 6
【样例输出】
0
【评测用例规模与约定】
对于所有评测用例,1 ≤ n ≤ 30, 1 ≤ m ≤ 30。
用dfs
//TLE
#include<bits/stdc++.h>
using namespace std;
int cnt, n, m;
void dfs(int x, int y) {
if (x == n && y == m) { cnt++; return; }
if(x > n || y > m)return ;
if (x % 2 == 0 && y % 2 == 0)return;
dfs(x + 1, y);
dfs(x, y + 1);
}
int main() {
freopen("in.txt", "r", stdin);
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
if (n % 2 == 0 && m % 2 == 0) { cout << 0; return 0; }
dfs(1, 1);
cout << cnt << endl;
}
用动态规划
//DP
#include<bits/stdc++.h>
using namespace std;
long long dp[40][40];
int main() {
//freopen("in.txt", "r", stdin);
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int n, m; cin >> n >> m;
if (n % 2 == 0 && m % 2 == 0)cout << 0;//如果终点就是无法走进的点直接输出0
else {
for(int i = 1;i <= n;++i)
for (int j = 1; j <= m; ++j) {
if (i == 1 && j == 1) {
dp[i][j] = 1;
continue;
}
if ((i & 1) || (j & 1))
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
cout << dp[n][m];
}