DFS解马走日问题

问题描述

在n*n的棋盘中,马只能走”日”字。马从位置(0,0)出发,把棋盘的每一格都走一次且只走一次。找出所有路径。 5*5的棋盘上,有304种解。


问题分析
搜索过程是从(0,0)出发,按照深度优先的原则,从8个方向中尝试一个可以走的点,直到尝试过所有的方向,走完棋盘上的所有点,得出所有的解。

马走日问题可以看成是在层数为n*n的8叉树中,找出所有的解。

#include "stdio"

int N =5;//棋盘大小为5*5
int martic[N][N];//代表棋盘的数组
int count = 0;//走的步数
int solution = 0;//方法数量
int step[8][2] = {{-1,-2},{-2,-1}, {-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};//要走的八个方向

int isok(int x,int y)//判断这一步是否符合规则
{
	if ((x>=0&&x<N&&y>=0&&y<N&&martic == 0))
	{
		return true;
	}
	else
	{
		return false;
	}
}

void display()//如果整个棋盘已经走满,就输出整个棋盘
{
	printf("the %d solution:\n",++solution);
	for(int i = 0;i < N;i++)
	{
		for(int j = 0;j < N;j++)
		{
			printf("%d  ",martic[i][j]);
		}
		printf("\n");
	}	
}

void DFS(int x,int y)
{
	int nextx,nexty;
	for (int i = 0; i < 8; ++i)
	{
		nextx = x + step[i][0];
		nexty = y + step[i][1];

		if (isok(nextx,nexty))//发现
		{
			
			if (count != (N*N-1))
			{
				count++;
				martic[nextx][nexty] = count;
				DFS(nextx,nexty);//递进 和 回溯
				martic[nextx][nexty] = 0;
				count--;
			}
			else
			{
				display();//满足条件,输出
			}
		}
	}}

int int main(int argc, char const *argv[])
{
	count = 1;
	martic[0][0] = 1;
	DFS(0,0);
	return 0;
}


    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/djd1234567/article/details/47964849
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞