(1)
(2)
(3)
(4)
需求分析
1、任务:(一):设置一个含有{x,y,di}变量的结构体。
int
(三):判断该位置是否能走(是否已走过,或超出8X8的矩阵)
(四)对马走的下一个可能方向按一定顺序进行处理。将马可能走的下一个方向按照下下个方向能走的度进行从小到大的排序,并且压入栈中(不能通过的标记为-1)
(五):处理棋盘。马的行走路线,并按求出的行走路线,将数字1,2,…,64依次填入8X8的方阵输出之
定义curstep=1,mata[x][y]=1;((x,y)为用户输入的初始数据)
判断path是否为空,
若不为空,
判断path的栈顶元素的di是否小于0
否则
测试数据:
在8乘8的矩阵中输出1~64的数,且没有重复的。
#include<iostream>
using namespace std;
#include<stack>
#define lenx 8
#define leny 8
#define num lenx*leny
struct Data
{
int x;
int y;
int di;//0~7
};
class MaTa
{
public:
MaTa();
~MaTa();
bool Pass(Data );
void Sort(Data );
Post GetNext(Data,int);//找下一个最优点的位置
bool Deal(Post );//处理棋盘
void Print();//输出结果
private:
int **mata; //马踏棋盘数组
int usenum;
};
MaTa::MaTa()
{
mata=new int*[lenx];
for(int i=0;i<lenx;i++)
{
mata[i]=new int[leny];
for(int j=0;j<leny;j++)
mata[i][j]=0;//表赋空
}
}
MaTa::~MaTa()
{
for (int i = 0; i < lenx; i++)
if (mata[i] != NULL)
delete [] mata[i];
if (mata != NULL)
delete[] mata;
}
bool MaTa::Pass(Data c)
{
return (c.x>-1 && c.x<8 && c. y>-1 && c.y<8 && mata[c.x][c.y]==0);
}
void MaTa::Sort(Data c)
{
usenum=lenx;
int htrx[lenx]={-2,-1,1,2,2,1,-1,-2};
int htry[leny]={1,2,2,1,-1,-2,-2,-1};
int k,temp;
Post newseat;
int du[lenx];
for(int i=0;i<lenx;i++)
{
k=0;
newseat.x=c.x+htrx[i];
newseat.y=c.y+htry[i];
if(Pass(newseat))
for(int j=0;j<leny;j++)
{
newseat.x+=htrx[j];
newseat.y+=htry[j];
if(Pass(newseat))
k++;
}
else
usenum--;
du[i]=k;
}
for(int i=0;i<usenum-1;i++)
for(int j=i;j<usenum;j++)
if(du[j]<du[j+1])
{
temp=htrx[j];
htrx[j]=htrx[j+1];
htrx[j+1]=temp;
temp=htry[j];
htry[j]=htry[j+1];
htry[j+1]=temp;
}
}
Post MaTa::GetNext(Data c,int di)//找下一个点位置-----------------------------------------------
{
Sort(c);
c.x+=htrx[di];
c.y+=hrty[di];
return c;
}
bool MaTa::Deal(Data start)//处理棋盘 ---------------------------------------------------
{
int curstep=1; //足迹
stack<Data> path(num);
Data curpos; //当前位置的坐标
Data e;
e.di=0;
curpos=start;
do{
if( Pass(curpos))
{
mata[curpos.x][curpos.y]=curstep++;
e.seat.x=curpos.x;
e.seat.y=curpos.y;
e.di=-1;
path.Push(e);
if(curstep==num)
return true;
else
curpos=GetNext(curpos,e.di);
}
else
{
e=path.top();
path.pop();
curstep--;
while(e.di==usenum && !path.empty()){
mata[e.seat.x][e.seat.y]=0;
e=path.top();
curdu=e.di+1;
path.pop();
curstep--;
curpos.x=e.seat.x;
curpos.y=e.seat.y;
}
if(e.di<usenum){
e.di++;
path.push(e);
curstep++;
curpos=GetNext(curpos,e.di);
}
}
} while(!path.empty());
return false;
}
void MaTa::Print()//输出结果-------------------------------------------------------------
{
for(int i=0;i<lenx;i++)
{
for(int j=0;j<leny;j++)
if(mata[i][j]>=0 && mata[i][j]<10)
cout<<" "<<mata[i][j];
else
cout<<" "<<mata[i][j];
cout<<endl;
}
}
int main()
{
MaTa m_mata;
Data start;
cout<<"请输入开始位置的坐标: "<<endl;
cin>>start.x>>start.y;
if( m_mata.Deal(start))
{
cout<<"马走遍全部64个格子"<<endl;
m_mata.Print();
}
else
cout<<"马不能走遍所有的格子"<<endl;
system("pause");
return 0;
}