Most efficient algorithm to find the biggest square in a two dimension map

前端 未结 5 515
长情又很酷
长情又很酷 2021-02-02 04:03

I would like to know the different algorithms to find the biggest square in a two dimensions map dotted with obstacles.

An example, where o would be obstacl

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 04:33

    The following SO articles are identical/similar to the problem you're trying to solve. You may want to look over those answers as well as the responses to your question.

    • Dynamic programming - Largest square block
    • dynamic programming: finding largest non-overlapping squares
    • Dynamic programming: Find largest diamond (rhombus)

    Here's the baseline case I'd use, written in simplified Python/pseudocode.

    # obstacleMap is a list of list of MapElements, stored in row-major order
    max([find_largest_rect(obstacleMap, element) for row in obstacleMap for element in row])    
    
    def find_largest_rect(obstacleMap, upper_left_elem):    
        size = 0    
        while not has_obstacles(obstacleMap, upper_left_elem, size+1):    
            size += 1    
        return size    
    
    def has_obstacles(obstacleMap, upper_left_elem, size):    
        #determines if there are obstacles on the on outside square layer    
        #for example, if U is the upper left element and size=3, then has_obstacles checks the elements marked p.    
        # .....    
        # ..U.p    
        # ....p    
        # ..ppp    
        periphery_row = obstacleMap[upper_left_elem.row][upper_left_elem.col:upper_left_elem.col+size]    
        periphery_col = [row[upper_left_elem.col+size] for row in obstacleMap[upper_left_elem.row:upper_left_elem.row+size]    
        return any(is_obstacle(elem) for elem in periphery_row + periphery_col)
    
    def is_obstacle(elem):    
        return elem.value == 'o'    
    
    class MapElement(object):    
        def __init__(self, row, col, value):    
            self.row = row    
            self.col = col    
            self.value = value    
    

提交回复
热议问题