gpt4 book ai didi

arrays - 如何在 Julia 中实现对二维数组的洪水填充?

转载 作者:行者123 更新时间:2023-12-01 23:54:12 26 4
gpt4 key购买 nike

问题

假设我有一个 2D 矩阵,其中一些随机整数为 01。如何洪水填充数组中的连续区域?

该算法特别适用于图像处理,在封闭区域中用另一种颜色填充一种颜色,就像油漆桶工具一样。

示例

假设我的数组是:

1 0 1 1 1 1 0
0 0 1 1 1 1 1
0 0 0 1 1 1 1
0 1 0 0 0 1 1
0 0 0 1 1 1 1

我想用 8 等其他内容填充右上角的 1 区域。我该如何实现?我知道该区域中任何 1 的索引,并且我有任何一个 1 的索引。

填充 8 后,数组应如下所示:

1 0 8 8 8 8 0
0 0 8 8 8 8 8
0 0 0 8 8 8 8
0 1 0 0 0 8 8
0 0 0 8 8 8 8

我的努力:

我尝试过以下方法:

  • 遍历数组中的每一项,检查它是否为 1,并将其替换为 8。显然这不起作用,因为它只是用 8 替换了所有 1。甚至该区域之外的 1 也被转换为 8
  • 使用相对坐标,检查 1 并用 8 替换我们给出的初始索引。简而言之,将所有值为 1 的邻居替换为 8。这也不起作用,因为它只替换了最近的 8 个邻居,并没有按照我想要的方式填充该区域。

最佳答案

瞧!答案在于递归:

该函数以 arr 形式接收您的数组,以及您以元组形式知道的 1 的坐标(或索引)(x, y) 作为参数。

当使用相对坐标时,我们对每个坐标调用Flood_fill函数:

function flood_fill(arr, (x, y))
# check every element in the neighborhood of the element at (x, y) in arr
for x_off in -1:1
for y_off in -1:1
# put the next part in a try-catch block so that if any index
# is outside the array, we move on to the next element.
try
# if the element is a 1, change it to an 8 and call flood_fill
# on it so it fills it's neighbors
if arr[x + x_off, y + y_off] == 1
arr[x + x_off, y + y_off] = 8
flood_fill(arr, (x + x_off, y + y_off))
end
catch
continue
end
end
end
end

关于arrays - 如何在 Julia 中实现对二维数组的洪水填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com