poj 2488 DFS水过

题目给出 n行m列的棋盘,问马可以全部的棋盘格都走过一遍吗,马以 L 型走


很土的办法,枚举起点,然后进行dfs并记录路径,注意要输出 字典序最小的一条路径,所以按照 程序中的 dx,dy方向数组就可以搞定了。。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 30;
bool vis[maxn][maxn], flag;
int dx[] = { -1, 1, -2, 2, -2, 2, -1, 1 },
		dy[] = { -2, -2, -1, -1, 1, 1, 2, 2 };//注意顺序
int n, m, end;
char s[60];

bool ok(int x, int y) {
	return x >= 0 && x < n && y >= 0 && y < m;
}

void dfs(int x, int y, int cnt, char *s) {
	if (flag)
		return;
	if (cnt == end) {
		puts(s);
		flag = true;
		return;
	}
	for (int i = 0; i < 8; i++) {
		int xx = x + dx[i], yy = y + dy[i];
		if (ok(xx, yy) && !vis[xx][yy]) {
			vis[xx][yy] = true;
			s[cnt] = yy + 'A';
			s[cnt+1] = xx + '1';
			dfs(xx, yy, cnt+2, s);
			vis[xx][yy] = false;
		}
	}
}

int main() {
	int t;
	int cas=0;
	scanf("%d", &t);
	while (t--) {
		printf("Scenario #%d:\n",++cas);
		scanf("%d%d", &n, &m);
		end = n * m * 2;
		flag = false;
		for (int j = 0; j < m; j++) {//先枚举列,以得到最小字典序
			for (int i = 0; i < n; i++) {
				memset(vis, 0, sizeof(vis));
				memset(s, 0, sizeof(s));
				s[0] = j + 'A';
				s[1] = i + '1';
				vis[i][j]=true;//记得标记。。
				dfs(i, j, 2, s);
				if (flag)
					goto endloop;
			}

		}
		endloop: if (!flag)
			puts("impossible");
		puts("");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值