Non-recursive implementation of Flood Fill algorithm?

前端 未结 3 1147
失恋的感觉
失恋的感觉 2021-01-02 05:32

I\'m working on a small drawing application in Java. I\'m trying to create a \'bucket-fill\' tool by implementing the Flood Fill algorithm.

I tried using a recursion

3条回答
  •  别那么骄傲
    2021-01-02 05:47

    You basically have two ways to implement a flood fill algorithm non-recursively. The first method has been clearly explained by sukunrt in which you use a queue to implement breadth first search.

    Alternatively, you can implement the recursive DFS non-recursively by using an implicit stack. For example, the following code implements a non-recursive DFS on a graph that has nodes as integers. In this code you use an array of Iterator to keep track of the processed neighbors in every node's adjacency list. The complete code can be accessed here.

    public NonrecursiveDFS(Graph G, int s) {
            marked = new boolean[G.V()];
    
            // to be able to iterate over each adjacency list, keeping track of which
            // vertex in each adjacency list needs to be explored next
            Iterator[] adj = (Iterator[]) new Iterator[G.V()];
            for (int v = 0; v < G.V(); v++)
                adj[v] = G.adj(v).iterator();
    
            // depth-first search using an explicit stack
            Stack stack = new Stack();
            marked[s] = true;
            stack.push(s);
            while (!stack.isEmpty()) {
                int v = stack.peek();
                if (adj[v].hasNext()) {
                    int w = adj[v].next();
                    if (!marked[w]) {
                        // discovered vertex w for the first time
                        marked[w] = true;
                        // edgeTo[v] = w;
                        stack.push(w);
                    }
                }
                else {
                    // v's adjacency list is exhausted
                    stack.pop();
                }
            }
        }
    

提交回复
热议问题