回溯算法(马踏棋盘)

简介: 回溯算法(马踏棋盘)

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

/*
   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;i
        horse[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;i
         RowStep[i]=rstep[i]; p->ColStep[i]=cstep[i]; } } void Prin(Horse *p) { int i,j; printf("No.%d\n",++CntHorse); for(i=0;i
          horse[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;i
       i=0;
         this->j=4;
      }
      void Cout(){
          cout<<"N0."<
        <
         =0&&a
          =0&&b
           HorseRun(); return 0; } 

运行效果如下:


20150113014656767.png

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

相关文章
|
6天前
|
算法
【算法】递归、搜索与回溯——汉诺塔
【算法】递归、搜索与回溯——汉诺塔
|
6天前
|
算法
【算法】递归、搜索与回溯——简介
【算法】递归、搜索与回溯——简介
|
2月前
|
机器学习/深度学习 人工智能 算法
回溯算法是怎样的
回溯算法,择优搜索:树的深搜+剪枝
|
2月前
|
机器学习/深度学习 存储 算法
Python5种算法回溯+剪枝、字典序、递归交换、计数回溯、迭代法 实现全排列ll【力扣题47】
Python5种算法回溯+剪枝、字典序、递归交换、计数回溯、迭代法 实现全排列ll【力扣题47】
|
2月前
|
算法 数据挖掘 开发者
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
|
3月前
|
算法
【算法系列篇】递归、搜索和回溯(四)
【算法系列篇】递归、搜索和回溯(四)
|
2月前
|
算法
【经典LeetCode算法题目专栏分类】【第3期】回溯问题系列:单词搜索、N皇后问题、判断有效数独、解数独
【经典LeetCode算法题目专栏分类】【第3期】回溯问题系列:单词搜索、N皇后问题、判断有效数独、解数独
|
2月前
|
机器学习/深度学习 存储 算法
LeetCode题目 90:五种算法 回溯\迭代\位掩码\字典树\动态规划实现 子集ll
LeetCode题目 90:五种算法 回溯\迭代\位掩码\字典树\动态规划实现 子集ll
|
3月前
|
算法 决策智能 索引
数据结构与算法 回溯
数据结构与算法 回溯
25 1
|
3月前
|
存储 算法
算法系列--递归,回溯,剪枝的综合应用(3)(上)
算法系列--递归,回溯,剪枝的综合应用(3)(上)
33 0
算法系列--递归,回溯,剪枝的综合应用(3)(上)

热门文章

最新文章