1. 程式人生 > >馬踏棋盤超簡潔遞迴80行完成

馬踏棋盤超簡潔遞迴80行完成

#include<stdio.h>
#include<windows.h>

#define MAX 8
#define NONE 0
#define START 1

int chess[MAX][MAX];
void initchess();
void traverchess(int i, int j, int num);
bool judge(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+1)
	{
		int x, y;
		for (x = 0; x < MAX; x++)
		{
			for (y = 0; y < MAX; y++)
			{
				printf("%4d   ", chess[x][y]);
			}
			printf("\n");
		}
		printf("\n");
		return;
	}
	if (judge(i,j))
	{
		chess[i][j] = num;
		traverchess(i + 2, j - 1, num + 1);
		traverchess(i + 2, j + 1, num + 1);
		traverchess(i - 2, j - 1, num + 1);
		traverchess(i - 2, j + 1, num + 1);
		traverchess(i + 1, j - 2, num + 1);
		traverchess(i + 1, j + 2, num + 1);
		traverchess(i - 1, j - 2, num + 1);
		traverchess(i - 1, j + 2, 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;
	}
}