1153. 马的周游问题

#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

bool been[8][8];
int dir[8][2];
int route[64];
int ct;
bool found;

struct pointInfo{
	int x;
	int y;
	int validUnvisitedNextNum;
	pointInfo(int nx, int ny) {
		x = nx;
		y = ny;
		validUnvisitedNextNum = 0;
	}
};

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));
    ct = 0;
    found = false;
}

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

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

bool compare(const pointInfo& a, const pointInfo& b) {
	return a.validUnvisitedNextNum < b.validUnvisitedNextNum;
}

void dfs(int x, int y) {
    if(ct == 64) {
    	found = true;
        return;
    }
    vector<pointInfo> next;
    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]) {
    	    pointInfo tmp(newx, newy);
    	    for(int j = 0; j < 8; j++) {
    	    	int tmpnewx = newx + dir[j][0];
                int tmpnewy = newy + dir[j][1];
                if(valid(tmpnewx, tmpnewy) && !been[tmpnewx][tmpnewy]) {
                	tmp.validUnvisitedNextNum++;
                }
    	    }
    	    next.push_back(tmp);
    	}
    }
    if(next.size() == 0) return;
    sort(next.begin(), next.end(), compare);
    for(int i = 0; i < next.size(); i++) {
        int newx = next[i].x;
        int newy = next[i].y;
        
        route[ct++] = point(newx, newy);
        been[newx][newy] = true;
        dfs(newx, newy); 
        if(found) {
            break;
        }
        been[newx][newy] = false;
        ct--;
    }
}

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

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

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值