flood fill算法

flood fill算法实现有三种形式

1、depth first search

2、breadth first search

3、breadth first scan

基本思想是找到还没有分配component的结点,并且计算哪个componetn包含此结点。

深度优先搜索算法是通过当前结点的所有邻接结点查找一步,对于还没有分配component的结点,赋值相应的component,然后在此结点上作递归。要求栈与图大小一样大,对于显示图问题不大,但是对于隐式图,结点灵敏可能会很大。

广度优先搜索,不是在新赋值的结点上作递归,而是将其添加到队列中。对于隐式图,要求队列大小可能会很大。

广度优先扫描,每个结点有两个值:component(表示属于哪个连通图)和visited(表示是否访问过),该算法遍历所有已经赋值component但是还没有访问的结点,同时将邻接结点赋值为当前的component。要求比较少的空间,消耗时间会相对长些。

伪代码:

# component(i) denotes the
# component that node i is in
 1 function flood_fill(new_component) 

 2 do
 3   num_visited = 0
 4   for all nodes i
 5     if component(i) = -2
 6       num_visited = num_visited + 1
 7       component(i) = new_component
 8       for all neighbors j of node i
 9         if component(j) = nil
10           component(j) = -2
11 until num_visited = 0 

12 function find_components 

13  num_components = 0
14  for all nodes i
15    component(node i) = nil
16  for all nodes i
17    if component(node i) is nil
18      num_components =
                 num_components + 1
19      component(i) = -2
20      flood_fill(component
                        num_components)
发布了1365 篇原创文章 · 获赞 71 · 访问量 140万+

猜你喜欢

转载自blog.csdn.net/wuli2496/article/details/104303599