P1002 [NOIP 2002 普及组] 过河卒
1.题目描述
棋盘上 A 点有一个过河卒,需要走到目标 B 点。卒行走的规则:可以向下、或者向右。同时在棋盘上 C 点有一个对方的马,该马所在的点和所有跳跃一步可达的点称为对方马的控制点。因此称之为“马拦过河卒”。
棋盘用坐标表示,A 点 (0,0)、B 点 (n,m),同样马的位置坐标是需要给出的。
现在要求你计算出卒从 A 点能够到达 B 点的路径的条数,假设马的位置是固定不动的,并不是卒走一步马走一步。
输入格式
一行四个正整数,分别表示 B 点坐标和马的坐标。
输出格式
一个整数,表示所有的路径条数。
输入
6 6 3 3
输出
6
说明/提示
对于 100% 的数据,1≤n,m≤20,0≤ 马的坐标 ≤20。
【题目来源】
NOIP 2002 普及组第四题
2.代码展示
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#define int long long
using namespace std;
int n, m, x, y;
int dp[25][25], visited[25][25];
// 马的8个控制点的相对坐标
int horse_dx[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
int horse_dy[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
void cal() {
// 输入的坐标转换为数组索引(题目中坐标从0开始)
// 马的位置
int horse_x = x;
int horse_y = y;
// 标记马及其控制点⚠️⚠️⚠️
if (horse_x >= 0 && horse_x <= n && horse_y >= 0 && horse_y <= m) {
visited[horse_x][horse_y] = true;
}
for (int i = 0; i < 8; i++) {
int nx = horse_x + horse_dx[i], ny = horse_y + horse_dy[i];
if (nx >= 0 && nx <= n && ny >= 0 && ny <= m) {
visited[nx][ny] = true;
}
}
// 初始化起点
dp[0][0] = 1; //⚠️⚠️⚠️注意初始化
// 状态转移
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (visited[i][j]) continue; // 如果当前点被控制,跳过
if (i == 0 && j == 0) continue; // 起点已初始化
// 从上方来的路径数
if (i > 0 && !visited[i - 1][j]) {
dp[i][j] += dp[i - 1][j];
}
// 从左方来的路径数
if (j > 0 && !visited[i][j - 1]) {
dp[i][j] += dp[i][j - 1];
}
}
}
cout << dp[n][m];
}
signed main() {
cin >> n >> m >> x >> y;
cal();
}