#include <stdio.h>
#include "stdafx.h"
#include <stdlib.h>
#define ROW 8
#define COL 8
typedef struct {
int x;
int y;
}Pos;
Pos IndexPos[8] = {{-2,-1},{-2,1},{-1,2},{-1,-2},{1,2},{1,-2},{2,1},{2,-1}};
Pos CurrPos;
Pos NextPos[8];
int step = 0;
int Array[ROW][COL] = {0};
int NextValues[8] = {100,100,100,100,100,100,100,100};
int CanJump(Pos data);
void Initial(void);
int GetNextPos(void);
void display(void);
int getValues(Pos data);
void Initial(void)
{
CurrPos.x = 5;
CurrPos.y = 5;
step ++;
Array[CurrPos.x][CurrPos.y] = step;
}
int CanJump(Pos data)
{
if (data.x < 0 || data.x >= ROW || data.y < 0 || data.y >= COL)
{
return 0;
}
else if (Array[data.x][data.y] > 0)
{
return 0;
}
else
{
return 1;
}
}
int GetNextPos(void)
{
int value = 0;
int i = 0;
Pos temp = {0,0};
for (i = 0; i < 8; i ++)
{
temp.x = CurrPos.x + IndexPos[i].x;
temp.y = CurrPos.y + IndexPos[i].y;
if (CanJump(temp))
{
NextPos[value].x = temp.x;
NextPos[value].y = temp.y;
value ++;
}
}
return value;
}
void display(void)
{
int i,j;
for (i = 0; i < ROW; i ++)
{
for (j = 0; j < COL; j ++)
{
printf("%4d",Array[i][j]);
}
printf("\n");
}
printf("\n");
}
int minNextPos(int num)
{
int value = 0;
int i;
int min = 100;
int temp;
for (i = 0; i < num; i ++)
{
temp = getValues(NextPos[i]);
printf("%d ",temp);
if (temp < min)
{
min =temp;
value = i;
}
}
return value;
}
int getValues(Pos data)
{
int value = 0;
int i;
Pos temp;
for (i = 0; i < 8; i ++)
{
temp.x = data.x + IndexPos[i].x;
temp.y = data.y + IndexPos[i].y;
if (CanJump(temp))
{
value ++;
}
}
return value;
}
/*
vood test(void)
{
value = GetNextPos();
index = minNextPos(value);
CurrPos.x = NextPos[index ].x;
CurrPos.y = NextPos[index ].y;
step ++;
Array[CurrPos.x][CurrPos.y] = step;
}*/
void display_nextpos(void)
{
int i;
for (i = 0; i < 8; i ++)
{
printf("NextPos[%d]: %d %d\n",i,NextPos[i].x,NextPos[i].y);
}
}
int main()
{
int KeepGoing = 1;
int value = 0;
int index;
Initial();
//test();
while (KeepGoing && step < ROW * COL)//ROW * COL
{
value = GetNextPos();
display_nextpos();
printf("value = %d\n",value);
if (value == 0)
{
KeepGoing = 0;
}
else if (value == 1)
{
CurrPos.x = NextPos[value - 1].x;
CurrPos.y = NextPos[value - 1].y;
step ++;
Array[CurrPos.x][CurrPos.y] = step;
}
else
{
index = minNextPos(value);
printf("index = %d\n",index);
CurrPos.x = NextPos[index ].x;
CurrPos.y = NextPos[index ].y;
step ++;
Array[CurrPos.x][CurrPos.y] = step;
}
display();
}
system("pause");
//display();
return 0;
}
初解骑士问题
最新推荐文章于 2023-09-02 12:50:49 发布