# 113.国际象棋

广搜,但本题如果广搜枚举马和象的话会超时。

广搜要只枚举马的走位,同时判断是否在对角巷直接走象

#include <iostream>
using namespace std;
const int N = 100005, mod = 1000000007;
using ll = long long;
int n, ans;
int dir[][2] = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, -1}, {-2, 1}};
int main() {
    int x1, y1, x2, y2;
    cin >> n;
    while (n--) {
        scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
        if (x1 == x2 && y1 == y2) {
            cout << 0 << endl;
            continue;
        }
        // 判断象走一步到达
        int d = abs(x1 - x2) - abs(y1 - y2);
        if (!d) {cout << 1 << endl; continue;}
        // 判断马走一步到达
        bool one = 0;
        for (int i = 0; i < 8; ++i) {
            int dx = x1 + dir[i][0], dy = y1 + dir[i][1];
            if (dx == x2 && dy == y2) {
                cout << 1 << endl;
                one = true;
                break;
            }
        }
        if (one) continue;
        // 接下来为两步的逻辑, 象走两步或者马走一步,象走一步
        // 象直接两步可以到达,这个计算是不是同颜色的格子,象可以在两步到达所有同颜色的格子
        int d2 = abs(x1 - x2) + abs(y1 - y2);
        if (d2 % 2 == 0) {
            cout << 2 << endl;
            continue;
        }
        // 接下来判断马 + 象的组合
        bool two = 0;
        for (int i = 0; i < 8; ++i) {
            int dx = x1 + dir[i][0], dy = y1 + dir[i][1];
            int d = abs(dx - x2) - abs(dy - y2);
            if (!d) {cout << 2 << endl; two = true; break;}
        }
        if (two) continue;
        // 剩下的格子全都是三步到达的
        cout << 3 << endl;
    }
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
上次更新:: 3/4/2025, 5:49:45 PM
@2021-2025 代码随想录 版权所有 粤ICP备19156078号