zoukankan      html  css  js  c++  java
  • 回溯算法(马踏棋盘)

    近期学习了回溯算法于是自己写了马踏棋盘的递归以及非递归方式的代码:
    /*
       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
    ",++CntHorse);
    	for(i=0;ihorse[i][j]); 
    		}
    		printf("
    ");
    	}
    	putchar('
    ');
    }
    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;
    }
    
    运行效果如下:

    (本人水平有限,若有不足之处欢迎大家交流)

  • 相关阅读:
    Jquery中的bind()方法绑定事件总结
    composer常用命令
    Activity四种启动模式
    谷歌搜索技巧
    关于Android studio Haxm加速器安装
    关于Ping和Tracert命令原理详解
    皮尔逊相关系数
    head标签
    wireshark抓包
    数据结构与算法自学系列之动态规划(一)
  • 原文地址:https://www.cnblogs.com/pzqu/p/9457660.html
Copyright © 2011-2022 走看看