首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现泛洪填充算法

实现泛洪填充算法
EN

Stack Overflow用户
提问于 2011-02-06 04:15:24
回答 2查看 583关注 0票数 0

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

代码语言:javascript
复制
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是如何耗尽的?

EN

回答 2

Stack Overflow用户

发布于 2011-02-13 12:34:41

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

如果我理解正确的话,您关心的是在使用"for each“语句时编辑队列的大小。算法伪代码在这方面是令人困惑的;其中它说:

代码语言:javascript
复制
For each element n of Q:
...
Continue looping until Q is exhausted.

你可以把它想象成:

代码语言:javascript
复制
while Q is not empty:
  dequeue element n of Q
  check the pixels

这将耗尽队列。

票数 0
EN

Stack Overflow用户

发布于 2011-02-06 04:22:19

在处理Q中的节点之后(在步骤11之后,在返回循环之前),删除它。最终,您将停止向Q添加元素,然后只需遍历其余的元素并逐个处理它们。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4909394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档