在 5 位置时:
(
𝑥,𝑦
)
→
(
𝑥+1,𝑦−2
)
在 6 位置时:
(
𝑥,𝑦
)
→
(
𝑥+2,𝑦−1
)
在 7 位置时:
(
𝑥,𝑦
)
→
(
𝑥+2,𝑦+1
)
在 8 位置时:
(
𝑥,𝑦
)
→
(
𝑥+1,𝑦+2
)
2 算法描述
qiShi(n,x,y)//n 为问题的规模,x,y 表示当前遍历的位置
输入:n 从 2 开始,因为第一个就是 x,y 表示的第一个遍历位置。
begin
if 所有的方格都遍历了 then
显示遍历的结果;并且返回到上一层。
for 对于每一个方向
计算出当前位置的当前方向的位置(n_x,n_y)。
if 该位置有效 then
对该位置进行标记 a[n_x][n_y]=n。
调用函数 qiShi(n+1,n_x,n_y)实现递归。
对该标志位置 a[n_x][n_y]置 0.
end
3 详细代码(采用 C++语言)
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<sstream>
#include<iomanip>
using namespace std;
/******************************递归法求解骑士遍历问************************************/
const int N=5;//5*5大小
int a[N][N];//棋盘
int d[8][2];//存储骑士的八个方向direction
int n_cnt=0;//统计一共多少个解
void display( int a[N][N])
{
for( int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
cout<<setw(4)<<a[i][j];
}
cout<<endl;
}
cout<<"________________________________"<<endl;
}
void initData()
评论0
最新资源