How can I group an array of rectangles into “Islands” of connected regions?

前端 未结 8 2003
难免孤独
难免孤独 2021-02-04 08:12

The problem

I have an array of java.awt.Rectangles. For those who are not familiar with this class, the important piece of information is that they provid

8条回答
  •  有刺的猬
    2021-02-04 08:46

    What you want is to find connected components. That is, imagine a graph whose vertices correspond to rectangles, and where there is an edge between two vertices if the corresponding rectangles intersect. Then, you want to find and label the connected components of this graph.

    Just finding the edges (determining, for each pair of rectangles, whether they intersect) takes O(n2) time, after which you can use either depth-first search or breadth-first search to find all the components in an additional O(E) time, where E < n2.

    In pseudocode (simple exercise to translate it to Java), it may look something like this:

    # r is the list of rectangles
    n = length of r (number of rectangles)
    
    #Determine "neighbors" of each vertex
    neighbors = (array of n lists, initially empty)
    for i in 1 to n:
        for j in 1 to n:
            if i!=j and r[i].intersects(r[j]):
                neighbors[i].append(j)
    
    #Now find the connected components
    components = (empty list of lists)
    done = (array of n "False"s)
    for i in 1 to n:
        if done[i]: continue
        curComponent = (empty list)
        queue = (list containing just i)
        while queue not empty:
            r = pop(head of queue)
            for s in neighbors[r]:
                if not done[s]:
                    done[s] = True
                    queue.push(s)
                    curComponent.push(s)
        #Everything connected to i has been found
        components.push(curComponent)
    
    return components
    

    I'm precomputing neighbors and using "done" labels to save the O(n) factor and make the whole thing O(n2). In fact, this algorithm is for general graphs, but because your graph is rather special — comes from rectangles — you can do even better: it is actually possible to solve the problem in O(n log n) time total, using segment trees.

提交回复
热议问题