poj-2488 A Knight's Journey

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int map[50][50];
int p, q;
int move[8][2] = {-1, -2, 1, -2, -2, -1, 2, -1, -2, 1, 2, 1, -1, 2, 1, 2};
int pn[50];
char qn[50];
int flag;

void dfs(int num, char ch, int step) {
	int i;
	if(step == p * q) {
		flag = 1;
		int k;
		for(k = 0; k < step; k++) {
			printf("%c%d", qn[k], pn[k]);
		}			
		printf("\n");
		return;
	}
	for(i = 0; i < 8; i++) {
		int tnum = num + move[i][0];
		char tch = ch + move[i][1];
		if(tnum < 0 || tch < 'A' || tnum >= p || tch >= 'A' + q || map[tnum][tch - 'A'] == 1 || flag) {
			continue;
		}
		else {
			map[tnum][tch - 'A'] = 1;
			pn[step] = tnum + 1;
			qn[step] = tch;
			dfs(tnum, tch, step + 1);
			map[tnum][tch - 'A'] = 0;
		}
	}
}

int main() {
	int n;
	scanf("%d", &n);
	int count = 0;
	while(n--) {
		scanf("%d %d", &p, &q);
		flag = 0;
		memset(map, 0, sizeof(map));
		printf("Scenario #%d:\n", ++count);
		map[0][0] = 1;
		pn[0] = 1;
		qn[0] = 'A';
		dfs(0, 'A', 1);
		if(!flag) printf("impossible\n");
		printf("\n");
	}
	return 0;
}


你可能感兴趣的:(深搜,poj-2488)