该算法没有参考经典的骑士走棋盘算法,而是采用普通的递归+回溯,因此效率比较低。
/******************************
作者:cncoderalex
博客:http://blog.youkuaiyun.com/cncoderalex
*******************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int N = 9;
int ChessBoard[N][N];
int StepX[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int StepY[] = {1, 2, 2, 1, -1, -2, -2, -1};
void Init()
{
memset(ChessBoard, 0, sizeof(ChessBoard));
}
bool KnightGo(int x, int y, int index)
{
ChessBoard[x][y] = index;
if(64 == index)
{
return true;
}
for(int i = 0; i < 8; i++)
{
int NextX = x + StepX[i];
int NextY = y + StepY[i];
if(NextX >= 1 && NextX <= 8 && NextY >=1 && NextY <=8 && ChessBoard[NextX][NextY] == 0)
{
if(KnightGo(NextX, NextY, index + 1))
return true;
}
}
ChessBoard[x][y] = 0;
return false;
}
void PrintChessBoard()
{
printf("http://blog.youkuaiyun.com/cncoderalex");
printf("\n\n");
for(int i = 1; i <= 8; i++)
{
for(int j = 1; j <= 8; j++)
{
printf("%2d ", ChessBoard[i][j]);
}
printf("\n");
}
}
int main()
{
Init();
KnightGo(1, 1, 1);
PrintChessBoard();
system("pause");
return 0;
}
本文地址:http://blog.youkuaiyun.com/cncoderalex/article/details/43227449 转载请标明出处,谢谢。