Anyone knows an algorithm for finding “shapes” in 2d arrays?

后端 未结 5 1400
不思量自难忘°
不思量自难忘° 2021-02-04 08:25

Let\'s take this map, where \'#\' illustrates a taken square and \'.\' illustrates a free square:

1 . # # # . .
2 . # . . # .
3 # . . . . #
4 . # # # . .
5 . . . . .          


        
5条回答
  •  春和景丽
    2021-02-04 08:44

    If you can convert your problem to a graph, what you are looking for is to identify connected components. And if a connected component does not contain an edge that is the boundary edge, then you have found the region that needs to be filled.

    If I define the graph like this:

    G = (V, E)
    V = {r1, r2, r3, r4, r5, r6, c1, c2, c3, c4, c5, c6}
    E = {(u, v) | u, v are elements of V && the cell(u, v) is not taken}
    

    Now run DFS to find all disconnected trees. Algorithm:

    for each u in V:
        color[u] = white
    
    for each u in V:
        if color[u] == white:
            contains_boundary_edge = False
            DFS-visit( u, contains_boundary_edge )
    
            if not contains_boundary_edge:
                Flood-fill( u )
    
    DFS-visit( u, contains_boundary_edge ):
        color[u] = gray
        for each v in adjacent( u ):
            if color[v] == white:
                if edge(u, v) is a boundary edge: // Can be easily identified if one of u, v is start or end row/col.
                    contains_boundary_edge = True
    
                DFS-visit( v, contains_boundary_edge )
    
        color[u] = black
    

提交回复
热议问题