7777733333 2022-05-28 00:40 采纳率: 87.5%
浏览 94
已结题

骑士周游问题:修改算法,判断找到的周游路径最后能否回到起点,并找到回到起点的路径

要求给出测试代码,谢谢!

from pythonds.graphs import Graph, Vertex

def knightGraph(bdSize):
    ktGraph = Graph()
    for row in range(bdSize):
        for col in range(bdSize):
            nodeId = posToNodeId(row, col, bdSize)
            newPositions = genLegalMoves(row, col, bdSize)
            for e in newPositions:
                nid = posToNodeId(e[0], e[1], 6)
                ktGraph.addEdge(nodeId, nid)
    return ktGraph


def legalCoord(x, bdSize):
    if x>=0 and x < bdSize: 
        return True
    else:
        return False

def posToNodeId(row,column,board_size):
    return (row * board_size) + column

def genLegalMoves(x, y, bdSize):
    newMoves = []
    moveOffsets = [(-1, -2), (-1, 2), (-2, -1), (-2, 1),
                (1, -2), (1, 2), (2, -1), (2, 1)]

    for i in moveOffsets:
        newX = x + i[0]
        newY = y + i[1]
        if legalCoord(newX, bdSize) and legalCoord(newY, bdSize):
            newMoves.append((newX, newY))
    return newMoves


def knightTour(n, path, u, limit):
    u.setColor('gray')
    path.append(u)
    if n < limit:
        nbrList = list(u.getConnections()) 
        i=0
        done = False
        while i < len(nbrList) and not done:
            if nbrList[i].getColor() == 'white':
                done = knightTour(n+1,path,nbrList[i],limit)
            i=i+1
        if not done: # 准备回溯
            path.pop()
            u.setColor('white')
    else:
        done = True


    return done



if __name__ == '__main__':
    # suppose board size is 6
    G = knightGraph(6)
    # you can choose any nodeid as the starting point
    u = G.getVertex(1)
    limit = 6 * 6
    # initial path is an empty list
    path = list()
    # we already have an initial node, therefore n equals 1
    n = 1
    # print whether successfully find a path that can traverse all of the nodes
    k = knightTour(n, path, u, limit)
    print("骑士周游的路径为:")
    for node in path:
       print(node.getId(), end=' ')

#text code
#骑士周游的路径为:
#1 9 5 16 8 0 13 2 6 14 10 21 29 33 25 12 20 24 32 28 17 4 15 19 30 26 34 23 27 31 

  • 写回答

2条回答 默认 最新

  • 关注

    img

    你题目的解答代码如下:

    from pythonds.graphs import Graph, Vertex
    
    def knightGraph(bdSize):
        ktGraph = Graph()
        for row in range(bdSize):
            for col in range(bdSize):
                nodeId = posToNodeId(row, col, bdSize)
                newPositions = genLegalMoves(row, col, bdSize)
                for e in newPositions:
                    nid = posToNodeId(e[0], e[1], 6)
                    ktGraph.addEdge(nodeId, nid)
        return ktGraph
    
    
    def legalCoord(x, bdSize):
        if x>=0 and x < bdSize:
            return True
        else:
            return False
    
    def posToNodeId(row,column,board_size):
        return (row * board_size) + column
    
    def genLegalMoves(x, y, bdSize):
        newMoves = []
        moveOffsets = [(-1, -2), (-1, 2), (-2, -1), (-2, 1),
                    (1, -2), (1, 2), (2, -1), (2, 1)]
    
        for i in moveOffsets:
            newX = x + i[0]
            newY = y + i[1]
            if legalCoord(newX, bdSize) and legalCoord(newY, bdSize):
                newMoves.append((newX, newY))
        return newMoves
    
    
    def knightTour(n, path, u, limit):
        u.setColor('gray')
        path.append(u)
        if n < limit+1:
            nbrList = list(u.getConnections())
            i=0
            done = False
            while i < len(nbrList) and not done:
                if n < limit and nbrList[i].getColor() == 'white' or n == limit and nbrList[i]==path[0]:
                    done = knightTour(n+1,path,nbrList[i],limit)
                i=i+1
            if not done: # 准备回溯
                path.pop()
                u.setColor('white')
        else:
            done = True
    
    
        return done
    
    
    
    if __name__ == '__main__':
        # suppose board size is 6
        G = knightGraph(6)
        # you can choose any nodeid as the starting point
        u = G.getVertex(1)
        limit = 6 * 6
        # initial path is an empty list
        path = list()
        # we already have an initial node, therefore n equals 1
        n = 1
        # print whether successfully find a path that can traverse all of the nodes
        k = knightTour(n, path, u, limit)
        print("骑士周游的路径为:")
        for node in path:
           print(node.getId(), end=' ')
    
    

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月5日
  • 已采纳回答 5月28日
  • 创建了问题 5月28日

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集