2011-02-05 121 views
0

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

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如何用尽?

回答

-1

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

+0

但是,向Q添加节点是否会扩展For循环的迭代范围?我认为还有另一种语言,在类似的情况下,如果我这样做,我会得到一个错误... – Voldemort 2011-02-05 20:55:39

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 

这将耗尽队列。