将马随机放在国际象棋的8×8棋盘的某个方格中,马按走棋规则进行移动。要求每个方格只进入一次,走遍棋盘上全部64个方格。
代码:
#include "stdafx.h"
#include <stdlib.h>
#include <time.h>
#define row 8
#define col 8
int cnt = 0;
int templater[row] = { - 1, - 2, - 2, - 1, 1, 2, 2, 1 };
int templatec[col] = { - 2, - 1, 1, 2, 2, 1, - 1, - 2 };
int mode = row;
void DFS(int r, int c, int chess[row][col], int sump)
{
if (sump == row*col + 1)
{
cnt++;
printf("输出第%d个解:\n", cnt);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
printf("%5d ", chess[i][j]);
}
printf("\n");
}
printf("\n\n\n");
return;
}
for (int k = 0; k < mode; k++)
{
if (r + templater[k] >= 0 && r + templater[k] < row && c + templatec[k] >= 0 && c + templatec[k] < col&&chess[r+templater[k]][c+templatec[k]]==0)
{
r = r + templater[k];
c = c + templatec[k];
chess[r][c] = sump;
DFS(r, c, chess, ++sump);
sump--;
chess[r][c] = 0;
r = r - templater[k];
c = c - templatec[k];
}
}
}
int main()
{
int chess[row][col];
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
chess[i][j] = 0;
}
}
int sump = 1;
chess[2][0] = 1;
DFS(2, 0, chess, ++sump);
system("pause");
return 0;
}