布线问题-分支限界法

from collections import deque

grid = [
    [0, 0, 1, 0, 0, 0, 0],
    [0, 0, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 1, 1, 0, 0],
    [1, 0, 0, 0, 1, 0, 0],
    [1, 1, 1, 0, 0, 0, 0],
    [1, 1, 1, 0, 0, 0, 0],
]


def findPath(start, finish, grid):
    m, n, newx, newy, l = len(grid), len(grid[0]), 0, 0, 0
    # 起始点 == 终止点
    if start == finish:
        return len
    # 四周加墙
    for i in range(m):
        grid[i][0] = grid[i][-1] = 1
    for i in range(n):
        grid[0][i] = grid[-1][i] = 1

    grid[start[0]][start[1]] = 2
    dct = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    here = start
    Q = deque()
    p(grid)
    # 查找路径
    while True:
        for d in dct:
            newx = here[0] + d[0]
            newy = here[1] + d[1]
            if grid[newx][newy] == 0:  # 未被选中
                grid[newx][newy] = grid[here[0]][here[1]] + 1
                p(grid)
                if (newx, newy) == finish:
                    break
                Q.append((newx, newy))
        if (newx, newy) == finish:
            break
        if len(Q) == 0:
            break
        here = Q.pop()
    # p(grid)
    # 计算路径
    pl = grid[finish[0]][finish[1]] - 2
    path = []
    here = finish
    for j in range(pl - 1, -2, -1):
        path.append(here)
        for d in dct:
            newx = here[0] + d[0]
            newy = here[1] + d[1]
            if grid[newx][newy] == j + 2:
                break
        here = (newx, newy)
    print(path[::-1])
    return len


def p(grid):
    for i in range(len(grid)):
        print(grid[i])
    print('\n')


findPath((2, 1), (3, 5), grid)

运行过程

[1, 1, 1, 1, 1, 1, 1]
[1, 0, 1, 1, 0, 0, 1]
[1, 2, 0, 0, 1, 0, 1]
[1, 0, 0, 1, 1, 0, 1]
[1, 0, 0, 0, 1, 0, 1]
[1, 1, 1, 0, 0, 0, 1]
[1, 1, 1, 1, 1, 1, 1]


[1, 1, 1, 1, 1, 1, 1]
[1, 0, 1, 1, 0, 0, 1]
[1, 2, 3, 0, 1, 0, 1]
[1, 0,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赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值