📜  a 0 离二维矩阵中心的最远距离(1)

📅  最后修改于: 2023-12-03 15:29:16.555000             🧑  作者: Mango

题目介绍

给定一个二维矩阵,其中某些位置被填充为字符 '0'。找到字符 '0' 离矩阵中心最远的距离。矩阵的中心由两个坐标确定:左上角的坐标为 (0, 0),右下角的坐标为 (m-1, n-1)

解题思路

本题可以采用广度优先搜索算法,从矩阵中所有的 '0' 位置出发,将每个位置看做是图中的一个节点,找到离中心最远的节点即可。需要注意的是,每个位置只能遍历一次,否则会出现重复计算的情况。

代码实现
def max_distance(matrix):
    m, n = len(matrix), len(matrix[0])
    queue = []

    # 找到所有 '0' 点
    for i in range(m):
        for j in range(n):
            if matrix[i][j] == '0':
                queue.append((i,j))

    # 广度优先搜索
    step = 0
    while queue:
        size = len(queue)
        for i in range(size):
            x, y = queue.pop(0)
            for dx, dy in [(1,0),(-1,0),(0,1),(0,-1)]:
                nx, ny = x+dx, y+dy
                if 0 <= nx < m and 0 <= ny < n and matrix[nx][ny] != '1':
                    queue.append((nx,ny))
                    matrix[nx][ny] = '1'
        step += 1

    return step-1
测试样例
matrix = [["1","1","1","1","1"],
          ["1","1","1","1","1"],
          ["1","1","0","1","1"],
          ["1","1","1","1","1"],
          ["1","1","1","1","1"]]
print(max_distance(matrix))   # 2

matrix = [["1","1","1","1","1"],
          ["1","1","1","1","1"],
          ["1","1","1","1","1"],
          ["0","1","1","1","1"],
          ["1","1","1","1","1"]]
print(max_distance(matrix))   # 2
时间复杂度

本算法的时间复杂度为 $O(mn)$,其中 $m$ 和 $n$ 分别表示矩阵的行数和列数。