POJ 2488 A Knight's Journey

本文介绍了一种使用深度优先搜索(DFS)算法在矩阵中查找序列的方法,通过设置起点并逐步探索可能路径,最终输出从起点到终点的所有路径序列。此算法适用于解决在二维网格中寻找特定路径的问题。

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

把起点设为A 1点,DFS找序列

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int r,c,flag,map[30][30];
int lc[1000][2];
int dir[8][2]={{-1,-2},{1,-2},{-2,-1},{2,-1},
               {-2,1},{2,1},{-1,2},{1,2}};
bool judge(int x,int y)
{
    if (x <= 0 || x > r || y <= 0 || y > c)
        return false;
    if (map[x][y] == 1)
        return false;
    return true;
}
void dfs(int x,int y,int cnt)
{
    int tx,ty,i;
    map[x][y]=1;
    lc[cnt][0]=x;
    lc[cnt][1]=y;
    if (cnt+1 == r*c)
    {
        for (i=0; i<=cnt; i++)
            printf("%c%d",lc[i][1]-1+'A',lc[i][0]);
        printf("\n\n");
        flag=1;
        return ;
    }
    for (i=0; i<8; i++)
    {
        tx=x+dir[i][0];
        ty=y+dir[i][1];
        if (judge(tx,ty))
        {
            dfs(tx,ty,cnt+1);
            if (flag == 1)
                break;
        }
    }
    map[x][y]=0;
}
int main()
{
    int i,T,prob;
    scanf("%d",&T);
    prob=1;
    while (T--)
    {
        scanf("%d%d",&r,&c);
        flag=0;
        memset(map,0,sizeof(map));
        printf("Scenario #%d:\n",prob);
        dfs(1,1,0);
        prob++;
        if (flag == 0)
            printf("impossible\n\n");
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值