標籤: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開始能搜到一條遍曆全棋盤
的路徑,那麼肯定從棋盤上的任意一個點作為起點都能搜出一條遍曆棋盤的路徑,並且題目
要求要按字典序輸出,所以只需從起點開始搜尋就可以了!
*/