Poj2488 A Knight's Journey

英文是硬傷 字典序輸出

14653114 493238731 2488 Accepted 164K 32MS C++ 1364B

#include <iostream>//Poj2488
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
using namespace std;


int n;
int p, q;
const int MAX_PQ = 27;
bool b[MAX_PQ][MAX_PQ];
int dx[] = { -2, -2, -1, -1, 1, 1, 2, 2 };//字典序
int dy[] = { -1, 1, -2, 2, -2, 2, -1, 1 };//lexicographically
char ch[MAX_PQ][3];


bool dfs(int x, int y, int cnt){
if (cnt == p*q)
return true;
int tmp = cnt;
bool flag = false;
for (int i = 0; i<8; i++){
int nx = x + dx[i], ny = y + dy[i];
if (0<nx&&nx <= q && 0<ny&&ny <= p&&b[nx][ny] == false){
flag = true;
tmp++;
ch[tmp][0] = 'A' + nx - 1;
ch[tmp][1] = '1' + ny - 1;
ch[tmp][2] = '\0';
b[nx][ny] = true;
if (dfs(nx, ny, tmp))
return true;
b[nx][ny] = false;
flag=false;
tmp--;
}


}
if (flag == false)
return false;
}
bool solve(){
memset(b, 0, sizeof(b));
memset(ch, 0, sizeof(ch));
b[1][1] = true;
ch[1][0] = 'A';
ch[1][1] = '1';
ch[1][2] = '\0';
return dfs(1, 1, 1);


}
int main(){
freopen("2488.txt", "r", stdin);
scanf("%d", &n);
int cnum = 1;
while (n--){
scanf("%d%d", &p, &q);
printf("Scenario #%d:\n", cnum++);
if (solve()){
for (int i = 1; i <= p*q; i++)
printf("%c%c", ch[i][0], ch[i][1]);
printf("\n");
}
else
printf("impossible\n");
printf("\n");
}
return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章