街区建车站问题

一个街区(矩阵),R是闲置地区,B是建筑,G是路障。选择一个闲置地区R建立车站,使得车站到所有建筑的距离之和最短。注:只能向上、下、左、右走,可以穿过R和B,无法穿过G。
例:
RRRRR
RBGRR
RRGBR
RGBRR
RRRRR
答案:选择[1, 3]的R建立车站,到3个B的距离分别是1、3、4,总距离之和最短,为8。
刚刚面试的题目,只会暴力解法。求大神教一下有什么巧妙方法吗?
matrix = [['R','R','R','R','R'],['R','B','G','R','R'],['R','R','G','B','R'],['R','G','B','R','R'],['R','R','R','R','R']]

ans = [float("inf")]
best = [None, None]

def checkPath(matrix):
    Buildings = []
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            if matrix[i][j] == 'B':
                Buildings.append([i, j])
    def checkPathSum(matrix, i, j):
        def checkPathNum(p1, p2, i, j, cur):
            if p1 == i and p2 == j:
                return cur
            tmp = matrix[p1][p2]
            matrix[p1][p2] = 'G'
            A, B, C, D = float("inf"), float("inf"), float("inf"), float("inf")
            if p1-1 >= 0 and matrix[p1-1][p2] != 'G':
                A = checkPathNum(p1-1, p2, i, j, cur+1)
            if p1+1 <= len(matrix)-1 and matrix[p1+1][p2] != 'G':
                B = checkPathNum(p1+1, p2, i, j, cur+1)
            if p2-1 >= 0 and matrix[p1][p2-1] != 'G':
                C = checkPathNum(p1, p2-1, i, j, cur+1)
            if p2+1 <= len(matrix[0])-1 and matrix[p1][p2+1] != 'G':
                D = checkPathNum(p1, p2+1, i, j, cur+1)
            matrix[p1][p2] = tmp
            return min(A, B, C, D)
        pathNum = 0
        for build in Buildings:
            pathNum += checkPathNum(build[0], build[1], i, j, 0)
            if pathNum >= ans[0]:
                return
        if pathNum < ans[0]:
            ans[0] = pathNum
            best[0], best[1] = i, j
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            if matrix[i][j] == 'R':
                checkPathSum(matrix, i, j)
    return ans[0], best

print(checkPath(matrix))


#笔试题目#
全部评论

相关推荐

03-27 20:14
前端工程师
投票
Spring启动:我在一嗨呆过,这么说吧 神仙单位,除了工资不怎么好 剩下的基本上天花板了,上班下班跟公务员似的,一天工作7个点,提供宿舍,宿舍离公司1km, 项目不着急,一般来说1天的活,你要个4天没人管你,我一天上班4个点在微信上跟别人聊天😂 去那边老自在了 但是也有可能是 我们组比较好
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客企业服务