您的位置:首页 > 其它

趣味算法-马踏棋盘

2012-02-14 22:36 281 查看
趣味算法-马踏棋盘

国际象棋64个格,按照马的走法,踏遍棋盘的每个格。

1) 使用递归算法尝试下一步是否满足条件,不满足条件则回退。

2) 若所有的格都被尝试一次则成功。

#include <stdio.h>

typedef struct _next_pos
{
int m_x;
int m_y;
} next_pos_t;

next_pos_t next_pos[8]={{-1,2},{-2,1},{-2,-1},{-1,-2},
{1,-2},{2,-1},{2,  1},{ 1, 2}};

int chess[8][8];
int nResult = 0;
next_pos_t arrRes[64];

int move(int nPosX, int nPosY)
{
int i = 0;
int nRet = 0;
for (i=0; i<8; i++)
{
if ((nPosX+next_pos[i].m_x < 0) || (nPosX+next_pos[i].m_x > 7)
|| (nPosY+next_pos[i].m_y < 0) || (nPosY+next_pos[i].m_y > 7))
{
continue;
}
if (chess[nPosX+next_pos[i].m_x][nPosY+next_pos[i].m_y] == 0)
{
chess[nPosX+next_pos[i].m_x][nPosY+next_pos[i].m_y] = 1;
nResult++;
arrRes[nResult].m_x = nPosX+next_pos[i].m_x;
arrRes[nResult].m_y = nPosY+next_pos[i].m_y;
nRet = move(nPosX+next_pos[i].m_x, nPosY+next_pos[i].m_y);
if (nRet == -1)
{
chess[nPosX+next_pos[i].m_x][nPosY+next_pos[i].m_y] = 0;
nResult--;
}
}
}

if (nResult == 63)
nRet = 0;
else
nRet = -1;

return nRet;
}

int main()
{
int i = 0;

memset(chess, 0, sizeof(chess));
memset(arrRes,0, sizeof(arrRes));
arrRes[0].m_x=0;
arrRes[0].m_y=0;
i = move(0, 0);

if (i == 0)
{
printf("find the solution\n");
for (i=0;i<64;i++)
{
if (i%8 == 0)
{
printf("\n");
}
printf("X=%d  Y=%d; ", arrRes[i].m_x, arrRes[i].m_y);
}
}
scanf("%d", &i);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: