|
| 1 | +from typing import List, Tuple |
| 2 | + |
| 3 | + |
| 4 | +def precomp_down_left_squares(m: List[List[int]]) \ |
| 5 | + -> Tuple[List[List[int]], List[List[int]]]: |
| 6 | + rows = len(m) |
| 7 | + cols = len(m[0]) |
| 8 | + |
| 9 | + down_sq = [[0 for _ in range(cols+1)] for _ in range(rows+1)] |
| 10 | + right_sq = [[0 for _ in range(cols+1)] for _ in range(rows+1)] |
| 11 | + |
| 12 | + for row in range(rows-1, -1, -1): |
| 13 | + for col in range(cols-1, -1, -1): |
| 14 | + down_sq[row][col] = 0 if m[row][col] == 0 else 1 + \ |
| 15 | + down_sq[row+1][col] |
| 16 | + right_sq[row][col] = 0 if m[row][col] == 0 else 1 + \ |
| 17 | + right_sq[row][col+1] |
| 18 | + |
| 19 | + return down_sq, right_sq |
| 20 | + |
| 21 | + |
| 22 | +def check_square(coords: tuple, sq_size: int, |
| 23 | + down_sq: List[List[int]], |
| 24 | + right_sq: List[List[int]]) -> bool: |
| 25 | + """ Check that the square has squares for all the sides, as required by the the size |
| 26 | + l r |
| 27 | + # # # # top |
| 28 | + # # |
| 29 | + # # |
| 30 | + # # # # bot |
| 31 | + <-----> sq_size |
| 32 | + """ |
| 33 | + top_left_col, top_left_row = coords |
| 34 | + bot_left_col, bot_left_row = top_left_col, top_left_row + sq_size-1 |
| 35 | + top_right_col, top_right_row = top_left_col + sq_size - 1, top_left_row |
| 36 | + |
| 37 | + if down_sq[top_left_row][top_left_col] < sq_size \ |
| 38 | + or right_sq[top_left_row][top_left_col] < sq_size: |
| 39 | + return False |
| 40 | + |
| 41 | + if down_sq[top_right_row][top_right_col] < sq_size \ |
| 42 | + or right_sq[bot_left_row][bot_left_col] < sq_size: |
| 43 | + return False |
| 44 | + |
| 45 | + return True |
| 46 | + |
| 47 | + |
| 48 | +def max_square_outline(matrix: List[List[int]]) -> List[tuple]: |
| 49 | + # Return the 4 coordonates, zero-indexed |
| 50 | + n = len(matrix) |
| 51 | + down_sq, right_sq = precomp_down_left_squares(matrix) |
| 52 | + |
| 53 | + for square_size in range(n, 0, -1): |
| 54 | + for row in range(0, n-square_size+1): |
| 55 | + for col in range(0, n-square_size+1): |
| 56 | + if check_square((row, col), square_size, down_sq, right_sq): |
| 57 | + return [ |
| 58 | + (row, col), |
| 59 | + (row+square_size - 1, col + square_size - 1) |
| 60 | + ] |
| 61 | + |
| 62 | + return [] |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + matrix = [ |
| 67 | + [0, 1, 1, 1, 1], |
| 68 | + [1, 0, 1, 0, 0], |
| 69 | + [1, 1, 1, 1, 0], |
| 70 | + [1, 0, 1, 1, 1]] |
| 71 | + |
| 72 | + print(f"Max square in test matrix is {max_square_outline(matrix)}") |
0 commit comments