马踏棋盘问题是旅行商(TSP)或哈密顿问题(HCP)的一个特例。在国际棋盘棋盘上,用一个马按照马步跳遍整个棋盘,要求每个格子都只跳到一次,最后回到出发点。这是一个 NP问题,通常采用回溯法或启发式搜索类算法求解。
在此采用栈进行回溯法求解
#include <iostream>
#include<stdlib.h>
#include <stdio.h>
#include <iomanip>
using namespace std;
const int StackInitSize=10;
const int StackInc=1;
typedef struct {
int x;
int y;
} Position;
typedef struct
{
int n=5;//迷宫规模n*n
int Board[10][10]={{0}};//棋盘最大规模
Position start;//马开始位置
}ChessBoard;
typedef struct {
int ord;
//顺序(第几步)
Position seat;
//位置
int di;
//查找方向
} SElemType;//马的当前状态
struct SStack
{
SElemType * base,*top;
int stacksize;
};
bool StackInit(SStack &S)
{
S.base=new SElemType[StackInitSize];
if(!S.base)
return false;
S.top=S.base;
S.stacksize=StackInitSize;
return true;
}
bool Push(SStack &S,SElemType e)
{
SElemType *base;
if(S.top-S.base==S.stacksize)
{
base=(SElemType*)realloc(S.base,(S.stacksize+StackInc)*sizeof(SElemType));
if(!base)
return false;
S.base=base;
S.top=S.base+S.stacksize;
S.stacksize+=StackInc;
}
*S.top=e;
S.top++;
return true;
}
bool Pop(SStack &S,SElemType &e)
{
if(S.top==S.base)
return false;
S.top--;
e=*S.top;
return true;
}
void HorseOnBoard(int n,int x,int y)
{
ChessBoard CBoard;
CBoard.start.x=x;
CBoard.start.y=y;
CBoard.n=n;
int h_move[8][2]={{2,1},{-1,2},{1,2},{-2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
int step=0;
int i=0;
SStack S;
StackInit(S);
Position p=CBoard.start;
SElemType horse;
horse.di=0;
horse.ord=step;
horse.seat=CBoard.start;
Push(S,horse);
do{
bool f=Pop(S,horse);
if(!f)
break;
if (step>=1)
{
i=horse.di+1;
CBoard.Board[horse.seat.x][horse.seat.y]=0;
step--;
}
for(i;i<8;i++)
{
p.x=horse.seat.x+h_move[i][0];
p.y=horse.seat.y+h_move[i][1];
if(CBoard.Board[p.x][p.y]==0&&(p.x<=CBoard.n-1)&&(p.x>=0)&&(p.y<=CBoard.n-1)&&(p.y>=0))
{
step++;
horse.di=i;
horse.ord=step;
Push(S,horse);
CBoard.Board[horse.seat.x][horse.seat.y]=step;
horse.seat=p;
i=0;
if(step==CBoard.n*CBoard.n-1)
{
step++;
CBoard.Board[horse.seat.x][horse.seat.y]=step;
Push(S,horse);
}
continue;
}
}
}while(step<CBoard.n*CBoard.n-1);
if(step<CBoard.n*CBoard.n)
cout<<"找不到合适的路径"<<endl;
else
{
cout<<"马在"<<n<<"*"<<n<<"的棋盘上的足迹如下:"<<endl;
for (int a = 0; a < n; a++) {
for(int b = 0; b < n; b++) {
cout<<setw(2)<<CBoard.Board[a][b]<<setw(2)<<' ';
}
cout<<' '<<endl;
}
}
}
int main()
{
HorseOnBoard(5,0,0);
return 0;
}
![](https://img-blog.csdnimg.cn/19ecb3d5afc3480cb331f450d062dadf.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5Y-rTHp5,size_20,color_FFFFFF,t_70,g_se,x_16)