马踏棋盘算法(骑士周游问题)

将马随机放在国际象棋的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;
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值