33,010
社区成员
发帖
与我相关
我的任务
分享
可以参考
#include <iostream.h>
#include "seetime.h"
#define WIDE 5
struct Node {
int x;
int y;
int h;
Node* next;
};
struct Stack {
Node* base;
Node* top;
int length;
};
void InitStack(Stack &L)
{
L.base = L.top = NULL;
L.length = 0;
}
void Push(Stack &L, Node* p)
{
p->next = L.top;
L.top = p;
L.length++;
}
void Pop(Stack &L)
{
Node* p = L.top;
L.top = L.top->next;
delete p;
L.length--;
}
void ClearStack(Stack &L)
{
while (L.top != NULL)
{
Node* p = L.top;
L.top = L.top->next;
delete p;
}
}
int a[] = {2,1,-1,-2,-2,-1,1,2};
int b[] = {1,2,2,1,-1,-2,-2,-1};
int board[WIDE][WIDE] = {0};
int visit[WIDE][WIDE] = {0};
int main()
{
Settime();
int cx, cy, key = -1;
int start_x = 1;
int start_y = 1;
visit[start_x][start_y] = 1;
Stack L;
InitStack(L);
Node* p = new Node;
p->x = start_x;
p->y = start_y;
Push(L, p);
while (L.length < WIDE * WIDE )
{
for (int i = 0; i < 8; i++)
{
cx = L.top->x + a[i];
cy = L.top->y + b[i];
if (cx >= 0 && cx < WIDE && cy >= 0 && cy < WIDE )
{
if (visit[cx][cy] == 0 )
{
if (i <= key)
{
continue;
}
Node* q = new Node;
q->x = cx;
q->y = cy;
q->h = i;
Push(L, q);
key = -1;
visit[cx][cy] = 1;
break;
}
}
}
if (i == 8)
{
cx = L.top->x;
cy = L.top->y;
visit[cx][cy] = 0;
key = L.top->h;
Pop(L);
}
if (L.length == 0)
{
cout<<"no";
return 0;
}
}
Node* t = L.top;
for (int i = L.length; i > 0; i--)
{
board[t->x][t->y] = i;
t = t->next;
}
for ( i = 0; i < WIDE; i++)
{
for (int j = 0; j < WIDE; j++)
{
cout<<board[i][j]<<" ";
}
cout<<"\n\n\n";
}
ClearStack(L);
cout<<Gettime()<<endl;
return 1;
}