【问题标题】:Matrix: Python adjacent矩阵:Python 相邻
【发布时间】:2020-01-05 09:20:44
【问题描述】:

我一直在尝试解决多个问题。现在卡在一个,似乎无法超越这一点。

给定表示每个服务器上存在一个新文件的二维数组,编写一个算法来确定将文件发送到所有服务器所需的最小小时数。

示例:

行数:4 列数:5 网格:

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

输出:2

因为:

在第一个小时结束时,他们的服务器的状态:

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

第二个小时,所有服务器状态:

[[1,1,1,1,1], [1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1,1]]

【问题讨论】:

  • 请分享您到目前为止所尝试的内容。
  • 看起来像家庭作业,缺少很多信息。矩阵代表什么?如果根据您的矩阵在任何服务器上都不存在第一个文件,您如何将第一个文件发送到任何服务器?每小时可以发送多少个文件?如果文件存在于 2 台服务器上而在 2 台服务器上丢失,是否可以并行发送?如果它在 1 台服务器上而在 3 台服务器上丢失,你能同时将它发送给所有 3 台服务器吗?等
  • 请求家庭作业帮助的问题必须包括您迄今为止为解决问题所做的工作的总结,以及您在解决问题时遇到的困难的描述。请阅读How to ask homework questionsedit 你的帖子。

标签: python-3.x algorithm matrix


【解决方案1】:

您可以通过广度优先搜索来解决这个问题,从具有 1 的位置开始:

def solve(mat):
    # collect positions that have a "1"
    frontier = []
    for y, row in enumerate(mat):
        for x, val in enumerate(row):
            if val:
                frontier.append((y,x))
    # Perform a BFS starting from these positions
    count = -1
    while len(frontier):
        count += 1
        newfrontier = []
        for y, x in frontier:
            # Get all neighbors of y, x:
            for y1, x1 in ((y-1, x), (y, x-1), (y+1, x), (y, x+1)):
                # If neighbor exists, and it has a zero:
                if (y1 >= 0 and y1 < len(mat) and 
                        x1 >= 0 and x1 < len(mat[0]) and mat[y1][x1] == 0):
                    # Visit this cell, and collect it for the next iteration
                    newfrontier.append((y1, x1))
                    mat[y1][x1] = 2 # mark as visited.
        frontier = newfrontier
    return count

res = solve([
    [0,1,1,0,1], 
    [0,1,0,1,0],
    [0,0,0,0,1],
    [0,1,0,0,0]
])

print(res) # 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2016-04-06
    相关资源
    最近更新 更多