pog.org 2488

來源:互聯網
上載者:User

標籤:os   io   for   art   問題   ar   amp   size   

/*
* POJ 2488
* DFS進行遍曆就好,記錄走過的路徑,只要不重複地走過p*q個方格就行了(結束條件)
*/

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int Max = 30;
int kase;
int p,q;
int vis[Max][Max]; //標記數組
//方向數組,按照字典序就好了
int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}};//8個方向
int path[Max*Max][2]; //用於記錄DFS走過的路徑
int flag;

void dfs(int x, int y, int step)
{

if(step == p*q) //走完了p*q格
{
cout<<"Scenario #"<<++kase<<":"<<endl;
for(int i=0; i<p*q; i++)
{
printf("%c%d",path[i][1]+‘A‘,path[i][0]+1); //注意我們記錄的路徑下標都是從0開始的,按我這裡的設計,先輸出y值
}
cout<<endl<<endl;
flag = 1;
return;
}


for(int d=0; d<8; d++)
{
int nx,ny; //只能做局部變數
nx = x + dir[d][0];
ny = y + dir[d][1];
if(!vis[nx][ny] && nx >= 0 && nx < p && ny >= 0 && ny < q)
{
vis[nx][ny] = 1;
path[step][0] = nx;
path[step][1] = ny;
dfs(nx, ny, step+1);
vis[nx][ny] = 0; //取消標幟
if(flag)
return;
}
}
}


int main()
{
int t;
while(scanf("%d",&t) != EOF)
{
kase = 0;
while(t--)
{
flag = 0;
memset(vis, 0, sizeof(vis));
scanf("%d %d",&p,&q);
path[0][0] = 0;
path[0][1] = 0;
vis[0][0] = 1;
dfs(0,0,1);

if(!flag)
{
cout<<"Scenario #"<<++kase<<":"<<endl;
cout<<"impossible"<<endl<<endl;
}
}
}
return 0;
}


/*
這裡注意幾個問題:
1、國際象棋,橫著是字母,豎著是數字。
2、是按字典序輸出的,所以搜尋方向上一定要注意!這裡是個坑。
3、忽略“The knight can start and end on any square of the board.”這句話,這也
    算是個坑,實際上只要從A1點開始搜尋就可以了,只要能從A1開始能搜到一條遍曆全棋盤
的路徑,那麼肯定從棋盤上的任意一個點作為起點都能搜出一條遍曆棋盤的路徑,並且題目
要求要按字典序輸出,所以只需從起點開始搜尋就可以了!
*/      
      
      
     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.