返回题解分享
讨论 / 题解分享/ 帖子详情

数字接龙(编程题) - 题解

#include <bits/stdc++.h>
using namespace std;

int n, k, now = 1, res;
int a[15][15], m[15][15], r[105], s[15][15]; // 棋盘,访问标记,路径方向,路径次序
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};

bool check(int xx, int yy, int dir) { // 判断是否交叉
    if (dir % 2 == 0) return false; // 如果方向是上,下,左,右就不用判断了
    switch (dir) {
        case 1:
            return s[xx - 1][yy] != -1 && s[xx][yy + 1] != -1 && abs(s[xx - 1][yy] - s[xx][yy + 1]) == 1;
        case 3:
            return s[xx + 1][yy] != -1 && s[xx][yy + 1] != -1 && abs(s[xx + 1][yy] - s[xx][yy + 1]) == 1;
        case 5:
            return s[xx + 1][yy] != -1 && s[xx][yy - 1] != -1 && abs(s[xx + 1][yy] - s[xx][yy - 1]) == 1;
        case 7:
            return s[xx - 1][yy] != -1 && s[xx][yy - 1] != -1 && abs(s[xx - 1][yy] - s[xx][yy - 1]) == 1;
    }
}

void dfs(int x, int y) {
    if (res == 1) return; // 有结果了直接返回
    if (x == n && y == n) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (m[i][j] == 0) return;
            }
        }
        res = 1;
        for (int i = 1; i <= n * n - 1; i++) { // 输出并结束
            cout << r[i];
        }
        exit(0);
    }
    for (int i = 0; i < 8; i++) {
        int tx = x + dx[i], ty = y + dy[i];
        if (tx < 1 || tx > n || ty < 1 || ty > n) continue; // 越界检查
        if (((a[x][y] + 1) % k) != a[tx][ty]) continue; // 数字序列检查
        if (m[tx][ty]) continue; // 访问标记检查
        if (check(x, y, i)) continue; // 交叉检查
        m[tx][ty] = 1; // 标记
        r[now] = i;
        s[tx][ty] = now;
        now++;
        dfs(tx, ty);
        now--; // 回溯
        s[tx][ty] = -1;
        m[tx][ty] = 0;
    }
}

int main() {
    memset(s, -1, sizeof(s));
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> a[i][j];
        }
    }
    if (a[1][1] != 0) { // 如果起点不是0,直接结束
        cout << "-1";
        return 0;
    }
    m[1][1] = 1; // 从(1,1)开始
    s[1][1] = 0; // 为了用now变量记录,下标从0开始
    dfs(1, 1); // 开搜!
    cout << "-1"; // 如果没有符合的
    return 0; 
}
0 回复 0 转发 1 喜欢 1 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!