C++ uses stack to realize Hamilton circuit

The chess horse is on a board with M rows and N columns (M, N is an even number greater than or equal to 6, and abs(MN)<=2), and a starting point is given. The horse jumps M*N steps and returns to the starting point. And each checker only jumps once. We call this circuit the Hamilton circuit.

Assuming any given a starting point: (input by the user), output one of the feasible solutions. (Assuming the chessboard is a 6*6 chessboard, fill in 1----36 in the chessboard, and each number represents the path of the horse)

The reference data is:

================================================ 

1. Initialization 

#include <iostream>
#include <iomanip>  //setw函数需要,对齐格式用
using namespace std;

const int maxn=105;
int board[maxn][maxn]={0};//棋盘
int num=0;
int m,n;//棋盘大小
int startX,startY;//起点位置
//马的8种走法,用数组做一个记录,左上为0号方向,顺时针下来到7号方向。
int dx[8]={-2,-2,-1, 1, 2, 2, 1,-1};
int dy[8]={-1, 1, 2, 2, 1,-1,-2,-2};

I drew a coordinate system to facilitate the understanding of dx[8] and dy[8] about the horse's movement, from 0 to 7 in a clockwise order, if the movement can be realized on the board, it will be executed.

Note: This figure is presented in the form of a coordinate system for easy understanding. The chessboard on which the code runs increases from the coordinate axis x = 0 to the right, and the coordinate axis y = 0 increases downward.

 

 2. Print the chessboard

setw(3) is the width of the printed font is 3

void output()
{
	for(int i = 0;i<m;i++)
    {
		for(int j = 0;j<n;j++)
			cout<<setw(3)<<board[i][j]<<" ";
		cout<<endl;
	}
}

 3. Determine whether the next step reaches the end

int toStart(int x,int y)
{
	for(int i = 0;i<8;i++)
		if(board[x+dx[i]][y+dy[i]]==1) //当前(x,y)的位置,8个方向中的其中一个位置能回到起点
			return 1;
	return 0;
}

4. The function of horse walking

bool moveHorse(int x,int y,int num)
{
	if(num==m*n+1&&toStart(x,y))//达到终点并且走满棋盘
    {
		output();//输出棋盘
		return true;//找到路线
	}
	int xx=0,yy=0;
    for(int i = 0;i<8;i++)//对马可以跳的8个方向进行探测,顺时针进行探测
    {
        xx=x+dx[i],yy=y+dy[i];//下一步的坐标
        if((board[xx][yy] == 0)&&(xx>=0&&xx<m&&yy>=0&&yy<n))
        {//下一步为空并且未越界
            board[xx][yy]=num;//在棋盘上记录马的步数
            if(moveHorse(xx,yy,num+1)) //在该位置的基础上继续执行马走 
				return true;
            board[xx][yy]=0;//若该点的路线不能到达终点,则该位置清零以便下一次查找
        }
    }
    return false;
}

 ================================================

main function

int main()
{
    //输入规模
    cout<<"输入规模;";
	cin>>m>>n;
	//输入起始位置
	cout<<"输入起始位置:" ;
	cin>>startX>>startY;
	board[startX][startY]=1;//将起始位置为1
	cout<<moveHorse(startX,startY,2); //初始位置的sum为1,故下一个位置的sum为2 
	return 0;
}

Guess you like

Origin blog.csdn.net/henry594xiaoli/article/details/125581005