马走日字--回溯法

   马走日字问题,在n*m的棋盘中,马只能走"日"字。马从位置(x,y)出发,把棋盘的每一格都走一次且只走一次。找出所有路径。 

  这个问题可以用回溯法解,每一步都有八种可能的走法,设马当前在(x,y)点,则它的可能走到:

  (x+1,x+2),(x+1,x-2),(x-1,x+2),(x-1,x-2),(x+2,x+1),(x+2,x-1),(x-2,x+1),(x-2,x-1)

  对每一种可能的走法试一遍,如果出界了或者已经走过了,则不用走了。试探一遍后,回溯。

  python实现:

'''
horse rides sun problem
use backtracking algorithm
author:ztp
create at:2015/1/19 15:06
'''

class HorseRides:
    def __init__(self, n, m, x, y):
        self.row = n
        self.column = m
        self.startx = x
        self.starty = y
        self.chessboard = [[0]*self.column for r in range(self.row+1)]
        self.sunx = [1, 1, 2, 2,-1,-1,-2,-2]
        self.suny = [2,-2, 1,-1, 2,-2, 1,-1]
        self.chessboard[self.startx][self.starty] = 1;
        self.count = 0;
    def check(self, x, y):
        if x >= self.row or y >= self.column or x < 0 or y < 0 or self.chessboard[x][y] != 0:
            return 0;
        return 1;
    def ride(self, x, y, step):
        for i in range(8):
            xx = x + self.sunx[i]
            yy = y + self.suny[i]
            if self.check(xx, yy) == 1:
                self.chessboard[xx][yy] = step;
                if step == self.row*self.column:
                    self.output();
                else:
                    self.ride(xx, yy, step+1)
                self.chessboard[xx][yy] = 0
    def output(self):
        self.count = self.count + 1
        print "count = %d" % self.count
        for i in range(self.row):
            print self.chessboard[i]
    def getCount(self):
        return self.count


if __name__ == "__main__":
    horseride = HorseRides(5,4,0,0)
    horseride.ride(0, 0, 2)
    print "total path: %d" % horseride.getCount()

  

转载于:https://www.cnblogs.com/zhutianpeng/p/3438978.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值