骑士周游,Knight Tour

骑士周游问题描述:

给定棋盘规模,和骑士起始点,如果起始能够不重复的走遍整个棋盘则成功,否则失败;

经典解法是递归;也可以用贪心算法,但贪心算法在有些情况下无法解决问题;

       Ss骑士周游问题tips(读者看过tips尽量自己算一下):

              1定义双数组,对应位置是一次移动的的大小(不用pair),总共是八个方向

       2递归解决,由于棋盘(区别迷宫)没有边界,所以要判定下一个将要走的方向是

否越界

       2判定下一个要走的方块是否已经走过(递归要求给每一个已经走过的方块打上记号)

#include<iostream>
using namespace std;
int board[5][5];
int movex[8] = { 1, 1, 2, 2, -1, -1, -2, -2 };
int movey[8] = { 2, -2, 1, -1, 2, -2, 1, -1 };  
there is no need to use a pair, double array is more easy
int cnt=0;
bool valid(int x, int y){
	if (x < 5&& y < 5 && x >= 0 && y >= 0) return true;
	else return false;
}
bool visit(int startx, int starty){
	board[startx][starty] = 1;
	cnt++;
	if (cnt == 25)return true;
	for (int i = 0; i != 8; i++){
		int x = startx + movex[i], y = starty + movey[i];
		if (cnt!=25&&valid(x, y)&&board[x][y]==0) visit(x, y);  
because there is no borders around the chessboard,so valid is necessary
	}                                                            
debug: left the condition of board[x][y]==0
	if (cnt != 25){ board[startx][starty] = 0; cnt--; return false; }
}
int main(){
		if (visit(4, 2)) cout << "ok" << endl;
	system("pause");
	return 0;
}
    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/love_code_love_life/article/details/54931244
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞