最近研究了马踏棋盘的问题,分享一下心得。
问题描述:将国际象棋的骑士放置任意位置,使其按规则不重复走完所有的棋格。
该问题的实质应该是:哈密顿路径的遍历。
首先画图分析一下具体环境:
如图所示,每个棋格有且仅有八个前进方向,标记为“1…8”,每个方向不一定合法(超出棋盘)
这时可以用递归回溯的思想对路径进行探索,思路是:
从方向1开始探索路径,一条路走到黑,发现走不了就回头走其他的路
再具体点的思路就是:
for i →1 to 8 //依次对八个方向进行探寻
if travel finish return //如果探索完毕返回
position→ new positon //获取新的棋格x,为原来棋格的儿子棋格
if position legal && new //如果新棋格x没超出棋盘 并且没有被探索过
travel(position) //对新棋格x进行探索
position reset //从探索中回到棋格x中
travel time reset //探索次数重置
更具体的可行性代码如下(第一次写,很随意很垃圾):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 马塔棋盘
{
class Program
{
static int tag = 1;
static int maxtri = 7;
//static int tempx, tempy;
static int[,] way = new int[8,8];
static void Main(string[] args)
{
//int x = int.Parse(Console.ReadLine());
//int y = int.Parse(Console.ReadLine());
way[0,0] = tag;
travel(0,0);
//foreach (var item in way)
//{
// Console.Write(item + "\t");
//}
Console.ReadKey();
}
public static void nextStep(int step,ref int x,ref int y)//棋格前进的方向
{
switch (step)
{
case (0):
{
x += 1;
y += 2;
break;
}
case (1):
{
x += 2;
y += 1;
break;
}
case (2):
{
x += 2;
y += -1;
break;
}
case (3):
{