数据结构——马踏棋盘题解(贪心算法)
- 使用循环建立棋盘与权值棋盘(权值为该位置可走的位置数量)
- 将当前步数写入棋盘数组中
- 开始探测下一步该走的位置, 分别测试八个方向
- 对可走位置进行查询权值,将权值最少的作为下一步的位置(每次都将步数最少的可走位置作为下一步的位置即贪心的体现)
- 循环2~4。
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define TRUE 1
#define ERROR 0
#define FALSE 0
#define M 8
#define N 8
int direction[2][9]={{0,-2,-1,1,2,2,1,-1,-2},{0,1,2,2,1,-1,-2,-2,-1}};
int pow[M][N];
int check[M][N],next[M][N];
struct Element
{
int x,y;
int d;
};
typedef struct LStack
{
Element data;
struct LStack *next;
}*PLStack;
typedef struct check
{
int x;
int y;
}Check;
int InitStack(PLStack &S)
{
S=NULL;
return OK;
}
int StackEmpty(PLStack S)
{
if(S==NULL)
return OK;
else
return FALSE;
}
int Push(PLStack &S, Element e)
{
PLStack p;
p=(PLStack)malloc(sizeof(LStack));
p->data=e;
p->next=S;
S=p;
return OK;
}
int Pop(PLStack &S,Element &e)
{
PLStack p;
if(!StackEmpty(S))
{
e=S->data;
p=S;
S=S->next;
free(p);
return OK;
}
else
return FALSE;
}
void Printf(int p[M][N]){
for(int i=0;i<M;i++){
for(int j=0;j<N;j++)
printf(" %2d ",p[i][j]);
printf("\n");
}
}
void InitWeight(){
for(int i=0;i<M;i++)
for(int j=0;j<N;j++)
pow[i][j]=0;
for(int i=0;i<M;i++){
for(int j=0;j<N;j++){
for(int dir=1;dir<=8;dir++){
int x1=i+direction[0][dir];
int y1=j+direction[1][dir];
if(x1>=0&&x1<=7&&y1>=0&&y1<=7)
pow[i][j]++;
}
}
}
}
void SetWeight(int x,int y) {
pow[x][y]=9;
for(int dir=1;dir<=8;dir++){
int x1=x+direction[0][dir];
int y1=y+direction[1][dir];
if(x1>=0&&x1<=7&&y1>=0&&y1<=7&&pow[x1][y1]!=9)
pow[x1][y1]--;
}
}
void UnSetWeight(int x,int y){
for(int dir=1;dir<=8;dir++){
int x1=x+direction[0][dir];
int y1=y+direction[1][dir];
if(x1>=0&&x1<=7&&y1>=0&&y1<=7&&pow[x1][y1]!=9){
pow[x1][y1]++;
pow[x][y]++;
}
}
}
int Step(Check start,PLStack &H) {
Element data;
int x=start.x-1,y=start.y-1;
int i=1;
while(i<=64){
check[x][y]=i;
SetWeight(x,y);
struct Element t,data;
int pow_min=9;
for(int dir=1;dir<=8;dir++){
int x1=x+direction[0][dir];
int y1=y+direction[1][dir];
if(x1>=0&&x1<=7&&y1>=0&&y1<=7&&pow[x1][y1]!=9)
{
if(pow_min>pow[x1][y1])
{
pow_min=pow[x1][y1];
t.d=dir;
t.x=x1;
t.y=y1;
}
}
}
data.x=x;
data.y=y;
data.d=t.d;
Push(H,data);
x=t.x;
y=t.y;
i++;
}
return OK;
}
int main(){
for(int i=0;i<M;i++)
for(int j=0;j<N;j++){
check[i][j]=0;
next[i][j]=0;
}
InitWeight();
PLStack H;
InitStack(H);
Check start;
printf("请输入起始坐标x y:");
scanf("%d%d",&start.x,&start.y);
Step(start,H);
Printf(check);
return 0;
}