您的位置:首页 > 其它

图的遍历算法-马遍历棋盘

2016-06-13 11:18 309 查看

题目

在n*m的棋盘中,马只能走日子,马从位置(x,y)处出发,把棋盘的每一点都走一次,且只走一次,找出所有的路径。

demo实现

棋盘设置为5*4,初始位置设置为(0.0)

算法重点

回溯

在递归后方将坐标置为初始状态0。

当路径错误的时候,能够把路径恢复到走之前的状态。

具体的实现,在注释中已经写得比较清楚。

#include<iostream>

using namespace std;

//坐标固定的马有八种走的方式
//用数组进行存储,方便在for中使用
int fx[8]= {1,2,2,1,-1,-2,-2,-1};
int fy[8]= {2,1,-1,-2,-2,-1,1,2};

static int mCount;
const static int n=5,m=4;
int a
[m];  //用int二维数组来表示走的路劲

void mFind(int x,int y,int dep);//寻找路径的递归
int mCheck(int x,int y);//判断坐标是否出界,是否已经走过
void output();//打印路径

int main()
{
int x=0,y=0;//选择(0,0)为初始点
mCount=0;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
a[i][j]=0;
a[x][y]=1;

mFind(x,y,2);

if(mCount==0)
cout<<"Non solution"<<endl;
else
cout<<endl<<"final count = "<<mCount<<endl;

}

void mFind(int x,int y,int dep)
{
int xx,yy;
for(int i=0; i<8; i++)
{
xx=x+fx[i];
yy=y+fy[i];
if(mCheck(xx,yy)==1)
{
a[xx][yy]=dep;
if(dep==n*m)
output();    //如果深度为n*m,那么表示遍历结束,就打印
else
mFind(xx,yy,dep+1);
a[xx][yy]=0;     //回溯,恢复未走坐标。(如果走错,要将走错的路径还原)
}
}
}

int mCheck(int x,int y)
{
//判断坐标是否出界,是否已经走过
if(x<0||y<0||x>=n||y>=m||a[x][y]!=0)
return 0;
return 1;
}

void output()
{
mCount++;
cout<<endl;
cout<<"count= "<<mCount;
for(int i=0; i<n; i++)
{
cout<<endl;
for(int j=0; j<m; j++)
cout<<a[i][j]<<" ";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: