回溯算法(马踏棋盘)
近期学习了回溯算法于是自己写了马踏棋盘的递归以及非递归方式的代码:
/*
Theme:马踏棋盘
回溯算法
Coder:秒针的声音
Time:2015.1.11
*/
#include
#include
#include
#define M 8
typedef struct node{
int horse[M][M];
int RowStep[M];
int ColStep[M];
}Horse;
Horse horse1;
int CntHorse=0;
void Init(Horse *p);
void HorseRun(int i,int j,int cnt);
void Prin(Horse *p);
int main(void)
{
FILE *fp;
fp=fopen("horse.txt","wt+");
Init(&horse1);
/*棋盘位于(0,0)--(7,7)位置*/
srand((unsigned)time(NULL));
int i=rand()%10;
int j=rand()%10;
while(i>7) i=rand()%10;
while(j>7) j=rand()%10;
HorseRun(i,j,1);
fclose(fp);
return 0;
}
//初始化
void Init(Horse *p)
{
int i;
for(i=0;ihorse[i/M][i%M]=0;
}
int rstep[M]={-2,-1,1,2,2,1,-1,-2};
int cstep[M]={1,2,2,1,-1,-2,-2,-1};
for(i=0;iRowStep[i]=rstep[i];
p->ColStep[i]=cstep[i];
}
}
void Prin(Horse *p)
{
int i,j;
printf("No.%d\n",++CntHorse);
for(i=0;ihorse[i][j]);
}
printf("\n");
}
putchar('\n');
}
void HorseRun(int i,int j,int cnt)
{
int times;
int a,b;//中间变量
for(times=0;times=0&&a=0&&b
/*
Theme:马踏棋盘(非递归)
Coder:秒针的声音
time:2015.1.13
*/
#include
using namespace std;
#define N 8
#include
class horse{
private:
int board[N][N];
int Step[2][N];
int stack[N*N];
int top;
int i;
int j;
int n;
public:
horse(){
n=1;
for(int i=0;ii=0;
this->j=4;
}
void Cout(){
cout<<"N0."<=0&&a=0&&bHorseRun();
return 0;
}
运行效果如下:
(本人水平有限,若有不足之处欢迎大家交流)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异