poj 2488 A Knight's Journey(DFS)

本文介绍了一种解决骑士周游问题的方法,通过深度优先搜索(DFS)算法找到骑士在棋盘上不重复地走遍所有格子的第一条字典序路径。代码详细展示了如何实现DFS,并给出了完整的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个棋盘,看骑士能不能不重复的走完所有的格子,输出按字典序排列的第一种路径

#include <cstdio>
#include <cstring>
const int MAXN = 30;
bool flag;
int g[MAXN][MAXN];
char path[60];
int n,m,res;
//要注意这里的顺序
int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};

void dfs(int row, int col, int cnt)
{
    if(flag) return;
    if(cnt == res)
    {
        puts(path);
        flag = true;
        return;
    }
    int tx,ty;
    for(int k = 0; k < 8; ++k)
    {
        tx = row + dir[k][0];
        ty = col + dir[k][1];
        if(tx < 0 || ty < 0 || tx >= n || ty >= m) continue;
        if(!g[tx][ty])
        {
            g[tx][ty] = 1;
            path[cnt*2] = ty + 'A';
            path[cnt*2+1] = tx + '1';
            dfs(tx,ty,cnt+1);
            g[tx][ty] = 0;
        }
    }
}

int main()
{
    int t;
    int time = 0;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&n,&m);
        flag = false;
        res = n*m;
        printf("Scenario #%d:\n",++time);
        for(int j = 0; j < m; ++j)
        {
            for(int i = 0; i < n; ++i)
            {
                memset(g,0,sizeof(g));
                memset(path,0,sizeof(path));
                path[0] = j + 'A';
                path[1] = i + '1';
                g[i][j] = 1;
                dfs(i,j,1);
                if(flag) break;
            }
            if(flag)break;
        }
        if(!flag)
            printf("impossible\n");
        printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值