poj2488(回溯板子题)

存着做模板

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

int dir[8][2] = { {-1, -2}, {1, -2}, {-2, -1}, {2, -1}, {-2, 1}, {2, 1}, {-1, 2}, {1, 2} };
int p, q, b[27][27];

struct Map {
	int y, x;
}ans[1000];

int judge(int x, int y ) {
	if(x <= 0 || x > q || y <= 0 || y > p)
		return 0;
	return 1;
}

int dfs(int x, int y, int step) {
	if(step == p * q)	return 1;

	int tx, ty;
	for(int i = 0; i < 8; i++) {
		ty = y + dir[i][0];
		tx = x + dir[i][1];
		if(judge(tx, ty) && b[tx][ty] == 0) {
			ans[step + 1].x = tx;
			ans[step + 1].y = ty;
			b[tx][ty] = 1;
			if(dfs(tx, ty, step + 1))
				return 1;
			b[tx][ty] = 0;
		}
	}
	return 0;
}

int main() {
	//freopen("input.txt", "r", stdin);
	int n;
	scanf("%d", &n);
	for(int j = 1; j <= n; j++) {
		memset(ans, 0, sizeof(ans));
		memset(b, 0, sizeof(b));
		int flag = 1;
		scanf("%d%d", &p, &q);
		for(int s = 1; s <= q; s++)
		for(int t = 1; t <= p; t++) {
			ans[1].x = s;
			ans[1].y = t;
			b[s][t] = 1;
			if(dfs(s, t, 1)) {
				printf("Scenario #%d:\n", j);
				for(int k = 1; k <= p*q; k++)
					printf("%c%d", (ans[k].x-1) + 'A', ans[k].y);
				printf("\n");
				flag = 0;
				break;
			}
		}
		if(flag) {
			printf("Scenario #%d:\n", j);
			printf("impossible\n");
		}
		putchar('\n');
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值