TikTok OA 面试真题解析:Binary Matrix 中到 1 的最少步数(BFS / 多源最短路)

31次阅读
没有评论

A binary matrix only has 0 or 1. For every element in the matrix, find the minimum number of steps to reach 1 (left, right, down, up).

Input:

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

Output:

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

这道题要求对矩阵中每个位置,计算到最近的 1 的最短步数,移动方向只能是上下左右。最自然的做法是把所有值为 1 的格子同时加入队列,做多源 BFS,按层向外扩展并记录距离;这样可以一次性求出每个 0 到最近 1 的最短路径,时间复杂度为 O(mn),适合面试中常见的网格最短路题型。

正文完
 0