DFS-A Knight's Journey

题目链接

注意:Then print a single line containing the lexicographically first path that visits all squares of the chessboard with knight moves followed by an empty line. (按字典序输出)

  • 所以在遍历的时候按照字典序进行遍历也就是最小了,

  • 要求有一个可以走完全部点的方案,因为要遍历完所有的点,那么肯定要经过A1点的,而且要求按字典序遍历,那么开始就从A1点开始遍历就好了,虽然题目说的是任何一个点都可以是起点(这很明显是个误导条件,然而我第一个写的时候还是傻傻地用循环去让试探每个点作为起点)。

  • 将方向可以存在数组中,不同的思维有不同的数组表达形式(这块要仔细检查)
    const int Dx[8]={-2,-2,-1,-1,1,1,2,2};
    const int Dy[8]={-1,1,-2,2,-2,2,-1,1};这个是我的方式

代码在这

/*
Test-2-A Knight's Journey 
思路:Dfs,
2017/3/19
*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 8+2;
const int Dx[8]={-2,-2,-1,-1,1,1,2,2};
const int Dy[8]={-1,1,-2,2,-2,2,-1,1};
int path[2][maxn*maxn];
int p,q;
int visited[maxn][maxn];
int Len;
bool Dfs(int i,int j,int length)
{
    if(length == Len)
        return true;        
    for(int k = 0;k < 8;++k)
    {
        int x = i + Dx[k];
        int y = j + Dy[k];
        if(x>0 && x<=q && y>0 && y<=p && !visited[x][y])
        {
                visited[x][y] = 1;
                path[0][length+1] = x;
                path[1][length+1] = y;
                if(Dfs(x,y,length+1))
                    return true;
                visited[x][y] = 0;  
        }
    }
    return false;
} 
 int main()
 {
    //std::ios::sync_with_stdio(false);
    //freopen("in(2).txt","r",stdin);
    //freopen("out2.txt","w",stdout);
    int n;
    int i,j;
    int cases=0;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d%d",&p,&q);
        Len = p*q;
        printf("Scenario #%d:\n",++cases);
        memset(visited,0,sizeof(visited));
        memset(path,0,sizeof(path));
        path[0][1] = 1;
        path[1][1] = 1;
        visited[1][1] = 1;
        if(Dfs(1,1,1))
        {
            for(int k = 1;k <= Len;++k)
                printf("%c%d",path[0][k]+'A'-1,path[1][k]);
        }
        else
        {
            printf("impossible");
        }
        printf("\n\n");
    }
    return 0;
 }
发布了48 篇原创文章 · 获赞 17 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章