Microsoft VO 面试真题解析:Flood Fill(数组 / DFS / BFS)

19次阅读
没有评论

Problem:

Given a 2D array of integers representing a paint canvas, where each integer represents a color, write a function that takes a point in the array and an integer representing a new color, and updates the canvas at that point along with all connected points of the same color with the new color.

Example 1:

Input:

const canvas = [[1, 2, 0, 1],
  [3, 2, 4, 3],
  [3, 1, 2, 0],
  [1, 0, 0, 4],
]

const row = 1;
const column = 1;
const newColor = 5;

这道题本质上是经典的 Flood Fill。你需要从给定的起点出发,找出所有与起点颜色相同、并且在上下左右四个方向上连通的格子,把它们统一改成新颜色。最常见的做法是用 DFS 或 BFS 遍历连通区域,先记录起点原颜色,再把访问到的同色邻居继续扩展;如果起点颜色和新颜色相同,也可以直接返回以避免重复处理。

正文完
 0