目前在看《数据结构》,这是数组后面的一道习题
warnsdorff规则是:骑士总是移向具有最少出口且没有到达过的方格,下面是代码
/*骑士巡游问题的Warnsdorff规则实现
*2013 1 15
*/
#include <stdio.h>
#include <stdlib.h>
int i, j;
int npos;
int m, k;
int ktmove1[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int ktmove2[8] = {1, 2, 2, 1, -1, -2, -2, -1};
static int board[8][8]; //
int nexti[8], nextj[8];
int l;
int min;
int exits[8];
int main (void)
{
printf ("Input the knight position:");
if (scanf ("%d%d", &i, &j) != 2)
{
printf ("Can't scanf \n");
exit(1);
}
if (i < 0 || i >= 8 ||j < 0 || j >= 8)
{
printf ("The position is too big or too small\n");
exit(1);
}
printf ("You start at (%d,%d)\n", i, j);
//start the tour
for (m = 1; m < 64; m++)
{
for (k = 0, npos = 0, l = 0; k < 8; k++)
{
if (i + ktmove1[k] >= 0 &&i + ktmove1[k] < 8 && j + ktmove2[k] >= 0 && j + ktmove2[8] < 8)
{
if (board[i + ktmove1[k]][j + ktmove2[k]] == 0)
{
npos++;
nexti[l] = i + ktmove1[k];
nextj[l] = j + ktmove2[k];
l++;
}
}
}
if (npos == 0)
{
printf ("There is no way\n");
break;
}
else if (npos == 1)
{
min = 0;
}
else
{
int L = l;
for (l = 0; l < L; l++)
{
exits[l]= 0;
for (k = 0; k < 8; k++)
{
if (nexti[l] + ktmove1[k] >= 0 && nexti[l] + ktmove1[k] < 8 && nextj[l] + ktmove2[k] >= 0 && nextj[l] + ktmove2[k] < 8)
{
if (board[nexti[l] + ktmove1[k]][nextj[l] + ktmove2[k]] == 0)
exits[l]++;
}
if (l == 0)
min = l;
else //The min is the least exits[l]'s l
{
if (exits[l] < exits[min])
min = l;
}
}
}
}
//take next step
i = nexti[min];
j = nextj[min];
board[i][j] = m;
}
printf ("The board is like that\n");
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
printf ("%3d",board[i][j]);
}
printf ("\n");
}
return 0;
}
运行和输出:
hyp@debian:~/code/data_structures$ ./a.out
Input the knight position:1 2
You start at (1,2)
There is no way
The board is like that
1 10 33 30 37 0 0 0
8 23 36 39 34 31 0 0
11 2 9 32 29 38 0 0
22 7 24 35 40 51 46 0
3 12 21 42 47 28 0 0
18 15 6 25 52 41 50 45
13 4 17 20 43 48 27 54
16 19 14 5 26 53 44 49