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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章