马踏棋盘(骑士周游列国)__贪心算法

最近研究了马踏棋盘的问题,分享一下心得。
问题描述:将国际象棋的骑士放置任意位置,使其按规则不重复走完所有的棋格。
该问题的实质应该是:哈密顿路径的遍历。
首先画图分析一下具体环境:
图一
如图所示,每个棋格有且仅有八个前进方向,标记为“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):
                    {
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值