java马踏棋盘回溯_马踏棋盘问题的回溯算法

这一个马踏棋盘的程序搞了很久都还是错误,到需要回溯的时候就发生错误,谁能帮我看下啊~~~~~程序如下:#include#include#defineN5templateclassStac...

这一个马踏棋盘的程序搞了很久都还是错误,到需要回溯的时候就发生错误,谁能帮我看下啊~~~~~

程序如下:

#include

#include

#define N 5

template

class Stack

{

public:

Stack(int MaxSize=N*N);

~Stack () { delete [] stack; }

inline bool IsEmpty() const { return (top==-1); }

inline bool IsFull() const { return (top==MaxTop); }

inline T Top() const;

inline Stack& Add(const T& x);

inline Stack& Delete(T& x);

private:

int top;

int MaxTop;

T *stack;

};

template

Stack::Stack(int MaxSize)

{

MaxTop=MaxSize-1;

stack=new T[MaxSize];

top=-1;

}

template

T Stack::Top() const

{

return stack[top];

}

template

Stack& Stack::Add(const T& x)

{

stack[top++]=x;

return *this;

}

template

Stack& Stack::Delete(T& x)

{

x=stack[top--];

return *this;

}

class Position

{

friend void FindPath();

private:

int row;

int col;

};

void FindPath()

{

Stack* path;

int board[N][N];

path=new Stack(N*N-1);

Position offset[8];

offset[0].row=-2; offset[0].col=1;

offset[1].row=-1; offset[1].col=2;

offset[2].row=1; offset[2].col=2;

offset[3].row=2; offset[3].col=1;

offset[4].row=2; offset[4].col=-1;

offset[5].row=1; offset[5].col=-2;

offset[6].row=-1; offset[6].col=-2;

offset[7].row=-2; offset[7].col=-1;

Position here;

here.row=0; here.col=0;

int step=1;

int i,j;

for (i=0;i

for (j=0;j

board[i][j]=0;

board[0][0]=step;

int option=0;

int lastOption=7;

while (step

{

int r,c;

while (option<=lastOption) //判断下个可走的方向

{

r=here.row+offset[option].row;

c=here.col+offset[option].col;

if (r>=0 && r=0 && c

if (board[r][c]==0) break;

option++;

}

if (option<=lastOption) //走一步,并入栈

{

here.row=r; here.col=c;

path->Add(here);

board[r][c]=++step;

option=0;

}

展开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值