A Knight‘s Journey
技術標籤:演算法
-
描述
Background
The knight is getting bored of seeing the same black and white squares again and again and has decided to make a journey
around the world. Whenever a knight moves, it is two squares in one direction and one square perpendicular to this. The world of a knight is the chessboard he is living on. Our knight lives on a chessboard that has a smaller area than a regular 8 * 8 board, but it is still rectangular. Can you help this adventurous knight to make travel plans?Problem
Find a path such that the knight visits every square once. The knight can start and end on any square of the board.
-
輸入
The input begins with a positive integer n in the first line. The following lines contain n test cases. Each test case consists of a single line with two positive integers p and q, such that 1 <= p * q <= 26. This represents a p * q chessboard, where p describes how many different square numbers 1, . . . , p exist, q describes how many different square letters exist. These are the first q letters of the Latin alphabet: A, . . . -
輸出
The output for every scenario begins with a line containing “Scenario #i:”, where i is the number of the scenario starting at 1. 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. The path should be given on a single line by concatenating the names of the visited squares. Each square name consists of a capital letter followed by a number. -
樣例
輸入
3
1 1
2 3
4 3
輸出
Scenario #1:
A1
Scenario #2:
impossible
Scenario #3:
A1B3C1A2B4C2A3B1C3A4B2C4
-
思路
深度優先搜尋,注意列數從小到大搜索保證輸出時按照字母表順序。
-
程式碼
#include<bits/stdc++.h>
using namespace std;
int visited[27][27] ;//用於標記某一位置是否走過
int N , p , q ;
int sum ;//用於判斷臨界條件
int visiting ;//記錄已走的步數與sum比較
int Count = 0 ;//記錄樣例的順序
int flag = 0 ;//判斷是否找到路
struct path{
int p ;
int q ;
};
path ans[1000] ;
void dfs(int i , int j ){
if(i > p || i < 1) return ;//臨界條件
if(j > q || j < 1) return ;
if(visited[i][j] == 1) return ;
visited[i][j] = 1 ;
visiting++ ;
ans[visiting].p = i , ans[visiting].q = j ;
if(visiting == sum ){
flag = 1 ;
for(int k = 1 ; k <= visiting ; k++){
printf("%c%d",ans[k].q - 1 + 'A' , ans[k].p ) ;
}
return ;
}
if(flag) return ;//j按照從小到大順序
dfs(i-1,j-2) ;
if(flag) return ;
dfs(i+1,j-2) ;
if(flag) return ;
dfs(i-2,j-1) ;
if(flag) return ;
dfs(i+2,j-1) ;
if(flag) return ;
dfs(i-2,j+1) ;
if(flag) return ;
dfs(i+2,j+1) ;
if(flag) return ;
dfs(i-1,j+2) ;
if(flag) return ;
dfs(i+1,j+2) ;
visited[i][j] = 0 ;
visiting-- ;
}
int main(){
cin >> N ;
while(N--){
cin >> p >> q ;
memset(visited,0 , sizeof(visited)) ;//初始化條件
sum = p*q ;
Count ++ ;
flag = 0 ;
printf("Scenario #%d:\n",Count) ;
for(int i = 1 ; i <= p ; i++ ){
for(int j = 1 ; j <= q ; j++ ){
visiting = 0 ;
dfs(i,j) ;
}
}
if(flag == 0 ) cout << "impossible" ;
if(N != 0) cout << endl << endl ;
}
return 0 ;
}
-
OJ
http://noi.openjudge.cn/ch0205/1490/