当先锋百科网

首页 1 2 3 4 5 6 7

这一个马踏棋盘的程序搞了很久都还是错误,到需要回溯的时候就发生错误,谁能帮我看下啊~~~~~程序如下:#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;

}

展开