实现洪水填充算法

时间:2011-02-05 20:15:24

标签: vb.net

我决定使用洪水填充算法为我的应用程序,使用维基百科的伪代码:

Flood-fill (node, target-color, replacement-color):
     1. Set Q to the empty queue.
     2. If the color of node is not equal to target-color, return.
     3. Add node to Q.
     4. For each element n of Q:
     5.  If the color of n is equal to target-color:
     6.   Set w and e equal to n.
     7.   Move w to the west until the color of the node to the west of w no longer matches target-color.
     8.   Move e to the east until the color of the node to the east of e no longer matches target-color.
     9.   Set the color of nodes between w and e to replacement-color.
    10.   For each node n between w and e:
    11.    If the color of the node to the north of n is target-color, add that node to Q.
           If the color of the node to the south of n is target-color, add that node to Q.
    12. Continue looping until Q is exhausted.
    13. Return.

我做得很好,直到我点击“继续循环直到Q耗尽”。 我不太明白。 Q怎么用尽了?

2 个答案:

答案 0 :(得分:0)

这是一种将递归函数转换为迭代函数的方法。您可以将其添加到队列中,而不是将每个像素推送到堆栈(递归)。你是对的,这将扩展迭代范围,但这就是你想要做的。它会在找到与种子颜色匹配的新像素时不断扩展。

如果我理解正确,你会担心在使用“for each”语句时编辑队列的大小。算法伪代码在这方面令人困惑;在哪里说:

For each element n of Q:
...
Continue looping until Q is exhausted.

将其视为:

while Q is not empty:
  dequeue element n of Q
  check the pixels

这会耗尽队列。

答案 1 :(得分:-1)

在Q中处理节点后(在步骤11之后,在返回循环之前),将其删除。最后你会停止向Q添加元素,然后你将完成剩下的工作并一次处理一个。

相关问题