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

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

#include <bits/stdc++.h>

using namespace std;
#define N 12
//输入
int n, k;
//起点终点
int qx = 0, qy = 0, zx, zy;
//地图
int g[N][N];
//标记没标记过
int f[N][N];
//这个点走的方向
int fx[N][N];
//记录方向用的
int bu[N * N];
//方向
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
//有没有结果
int res = 0;

//输出
void otto() {
    for (int i = 0; i < n * n - 1; ++i)
        cout << bu[i];
}

//搜索
void dfs(int x, int y, int bus, int zt) {
    //已经找到结果了,不找了
    if (res == 1)
        return;
    //坐标正确,步数正确,允许输出
    if (x == zx && y == zy && bus == n * n - 1) {
        //标记为找到
        res = 1;
        //调用函数把结果打出来
        otto();
        return;
    }
    //循环走方格
    if (zt == k - 1)
        zt = -1;
    //八个方向,顺时针就不用管字典序
    for (int i = 0; i < 8; ++i) {
        //一个新的点的俩坐标
        int vx = x + dx[i];
        int vy = y + dy[i];
        //标记 错号 出界
        if (f[vx][vy] || g[vx][vy] != zt + 1 || x < 0 || y < 0 || x >= n || y >= n)
            continue;
        //如果会交叉
        if (i == 1 && (fx[x][y + 1] == 7 || fx[x - 1][y] == 3))
            continue;
        if (i == 3 && (fx[x][y + 1] == 5 || fx[x + 1][y] == 1))
            continue;
        if (i == 5 && (fx[x][y - 1] == 3 || fx[x + 1][y] == 7))
            continue;
        if (i == 7 && (fx[x][y - 1] == 1 || fx[x - 1][y] == 5))
            continue;
        //开搜
        f[vx][vy] = 1;
        fx[x][y] = i;
        bu[bus] = i;
        dfs(vx, vy, bus + 1, g[vx][vy]);
        bu[bus] = -1;
        fx[x][y] = -1;
        f[vx][vy] = 0;
    }
}

int main() {
    //输入
    cin >> n >> k;
    zx = n - 1, zy = n - 1;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            cin >> g[i][j];
    //初始化一些数据
    memset(fx, -1, sizeof fx);
    memset(f, 0, sizeof f);
    memset(bu, -1, sizeof bu);
    //起点标成走过
    f[qx][qy] = 1;
    //我搜搜搜
    dfs(qx, qy, 0, 0);
    //没找到
    if (!res)
        cout << -1 << endl;
    return 0;
}
0 回复 0 转发 4 喜欢 1 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!