其他分享
首页 > 其他分享> > 【POJ】2488 A Knight‘s Journey

【POJ】2488 A Knight‘s Journey

作者:互联网

在这里插入图片描述
因为需要输出完整的访问路径,因此采用DFS比较好,注意因为题目要求按照字典序输出,因此direction数组只能有一种构造方式:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>

using namespace std;

int direction[8][2] = {
        {-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-2, 1}, {2, 1}, {-1, 2}, {1, 2}
};

const int N = 30;

bool visited[N][N];
int p, q;

bool DFS(int x, int y, int step, string ans){
    if(step == p * q){
        cout<<ans<<endl<<endl;
        return true;
    }
    for(int i = 0;i < 8;i++){
        int nx = x + direction[i][0];
        int ny = y + direction[i][1];
        if(nx < 0 || nx >= p || ny < 0 || ny >= q || visited[nx][ny]) continue;
        visited[nx][ny] = true;
        char col = ny + 'A';
        char row = nx + '1';
        if(DFS(nx, ny, step + 1, ans + col + row)) return true;
        visited[nx][ny] = false;
    }
    return false;
}

int main(){
    int n;
    scanf("%d", &n);
    for(int i = 0;i < n;i++){
        scanf("%d%d", &p, &q);
        printf("Scenario #%d:\n", i + 1);
        memset(visited, false, sizeof(visited));
        visited[0][0] = true;
        if(!DFS(0, 0, 1, "A1")) printf("impossible\n\n");
    }
    return 0;
}

标签:direction,int,Knight,nx,ny,Journey,POJ,visited,include
来源: https://blog.csdn.net/weixin_55267022/article/details/122748215