回溯算法(马踏棋盘)

近期学习了回溯算法于是自己写了马踏棋盘的递归以及非递归方式的代码:

/*
   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;
}

运行效果如下:
《回溯算法(马踏棋盘)》

《回溯算法(马踏棋盘)》 (本人水平有限,若有不足之处欢迎大家交流)

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/BTnode/article/details/42664805
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞