之前做了个深搜遍历求解的方法,未优化,一个下午没有结果,而且代码尚不够精简
看了一下优化方法,又重做了一个,基本不需要时间就能得到一个解
一共一百来行,沾沾自喜一下
#include<stdio.h>
#include<windows.h>
#define MAX 8
#define NONE 0
#define START 1
#define INFINITE 88888
int chess[MAX][MAX];
int gowhere[][2] = { { 2, -1 }, { 2, 1 }, { -2, 1 }, { -2, -1 }, { 1, 2 }, { 1, -2 }, { -1, -2 }, { -1, 2 } };//用二维数组更简单
void initchess();
void traverchess(int i, int j, int num);
bool judge(int i, int j);
int judgeminpath(int i, int j);
int main()
{
initchess();
int i, j;
scanf_s("%d%d", &i, &j);
traverchess(i, j, START);
system("pause");
}
void initchess()
{
int i, j;
for (i = 0; i < MAX; i++)
{
for (j = 0; j < MAX; j++)
{
chess[i][j] = NONE;
}
}
}
void traverchess(int i, int j,int num)
{
if (num == MAX*MAX)
{
int x, y;
chess[i][j] = MAX*MAX;
for (x = 0; x < MAX; x++)
{
for (y = 0; y < MAX; y++)
{
printf("%4d ", chess[x][y]);
}
printf("\n");
}
printf("\n");
return;
}
int recordc,count,min=INFINITE;
for (count = 0; count < 8; count++)//for循环为贪心算法核心,遍历坐标ij的周围八个点,并由judgeminpath函数返回八个点的中每个点的可走路数
{
if (!judge(i + gowhere[count][0], j + gowhere[count][1]))
{
continue;
}
int path = judgeminpath(i + gowhere[count][0], j + gowhere[count][1]);
if (min > path)
{
min = path;
recordc = count;
}
}
if (min!=INFINITE)
{
chess[i][j] = num;
traverchess(i + gowhere[recordc][0], j + gowhere[recordc][1], num + 1);
chess[i][j] = NONE;
}
}
bool judge(int i,int j)
{
if (i >= MAX || i < 0 || j >= MAX || j < 0)
{
return false;
}
if (chess[i][j] == NONE)
{
return true;
}
else
{
return false;
}
}
int judgeminpath(int i, int j)
{
int c;
int tag=0;
for (c = 0; c < 8; c++)
{
if (judge(i + gowhere[c][0], j + gowhere[c][1]))
{
tag++;
}
}
return tag;
}