1152. 简单的马周游问题

找到后break要放到深搜后面呢……被阴了几次

#include <iostream>
#include <cstring>

using namespace std;

bool been[5][6];
int dir[8][2];
int route[30];
int count;
bool found;

void initial() {
	dir[0][0] = -2, dir[0][1] = -1;
	dir[1][0] = -2, dir[1][1] = 1;
	dir[2][0] = 2, dir[2][1] = -1;
	dir[3][0] = 2, dir[3][1] = 1;
	dir[4][0] = -1, dir[4][1] = -2;
	dir[5][0] = -1, dir[5][1] = 2;
	dir[6][0] = 1, dir[6][1] = -2;
	dir[7][0] = 1, dir[7][1] = 2;
	memset(been, false, sizeof(been));
	memset(route, 0, sizeof(route));
	count = 0;
	found = false;
}

int point(const int x, const int y) {
	return x*6+y+1;
}

bool valid(const int x, const int y) {
	return (x >= 0 && x <= 4 && y >= 0 && y <= 5);
}

void dfs(int x, int y) {
	if(found) {
		return;
	}
	for(int i = 0; i < 8; i++) {
		int newx = x + dir[i][0];
		int newy = y + dir[i][1];
		if(valid(newx, newy) && !been[newx][newy]) {
			route[count++] = point(newx, newy);
			been[newx][newy] = true;
			if(count == 30) {
				found = true;
			}
			dfs(newx, newy); 
			if(found) {
				break;
			}
		    been[newx][newy] = false;
		    count--;
		}
	}
}

void print() {
	cout << route[0];
	for(int i = 1; i <= 29; i++) {
		cout << ' ' << route[i];
	}
	cout << endl;
}

int main() {
	int n;
	while(cin >> n && n != -1) {
		initial();
		route[count++] = n;
		int st_x = (n-1)/6, st_y = n%6-1;
		been[st_x][st_y] = true;
		dfs(st_x, st_y);
		print(); 
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值