1. 程式人生 > >Codeforces 1089E - Easy Chess - [DFS+特判][2018-2019 ICPC, NEERC, Northern Eurasia Finals Problem E]

Codeforces 1089E - Easy Chess - [DFS+特判][2018-2019 ICPC, NEERC, Northern Eurasia Finals Problem E]

題目連結:https://codeforces.com/contest/1089/problem/E

Elma is learning chess figures.

She learned that a rook can move either horizontally or vertically. To enhance her understanding of rook movement Elma’s grandmother gave Elma an 8 × 8 chess board and asked her to find a way to move the rook from a1 to h8 making exactly n moves, so that all visited cells are different.

A visited cell is the initial cell a1 and each cell on which the rook lands after a move.

Input

The input contains a single integer n (2 ≤ n ≤ 63) — the desired number of moves.

Output

Output a space-separated list of n+ 1 visited cells in the order they are visited by the rook.

All cells must be different. The list should start with a1 and end with h8. A solution always exists.

 

題意:

給你 $8 \times 8$ 的棋盤,有一個棋子車在 $a1$ 位置,現在要經過 $n$ 步移動到達 $h8$ 位置。

要求不能第二次到達曾經到達過的格子,且必須恰好移動 $n$ 步,請給出一種移動方案。

 

題解:

上來先敲個DFS,萬一能過呢?

然後本地跑了一下,發現在 $2 \le n \le 56$ 的範圍內跑的飛快,剩下也沒幾種情況了,乾脆特判了之後自己寫一個固定走法即可。

 

AC程式碼:

#include<bits/stdc++.h>
#define mk(x,y) make_pair(x,y)
using
namespace std; typedef pair<int,int> pii; int n; bool vis[10][10],ok; vector<pii> ans; void dfs(int x,int y,int d) { if(ok) return; if(d>n) return; if(d==n && x==8 && y==8) {ok=1;return;} for(int i=1;i<=8;i++) { if(!vis[i][y]) { ans.push_back(mk(i,y)); vis[i][y]=1; dfs(i,y,d+1); if(ok) return; ans.pop_back(); vis[i][y]=0; } if(!vis[x][i]) { ans.push_back(mk(x,i)); vis[x][i]=1; dfs(x,i,d+1); if(ok) return; ans.pop_back(); vis[x][i]=0; } } } int main() { while(cin>>n) { if(n<=56) { ans.clear(); memset(vis,0,sizeof(vis)); ans.push_back(mk(1,1)); vis[1][1]=1; ok=0; dfs(1,1,0); for(int i=0;i<ans.size();i++) { if(i>0) printf(" "); printf("%c%d",'a'+ans[i].first-1,ans[i].second); } printf("\n"); } else { for(int r=1;r<=6;r++) { if(r%2==0) { for(int c=8;c>=1;c--) printf("%c%d ",'a'+c-1,r); } else { for(int c=1;c<=8;c++) printf("%c%d ",'a'+c-1,r); } } printf("a7 a8 b8 b7 c7 c8 d8 d7 "); switch(n) { case 57: printf("h7 h8\n"); break; case 58: printf("e7 h7 h8\n"); break; case 59: printf("e7 f7 h7 h8\n"); break; case 60: printf("e7 f7 g7 h7 h8\n"); break; case 61: printf("e7 e8 f8 f7 h7 h8\n"); break; case 62: printf("e7 e8 f8 f7 g7 h7 h8\n"); break; case 63: printf("e7 e8 f8 f7 h7 g7 g8 h8\n"); break; } } } }