Leetcode 1239 Solution

This article provides solution to leetcode question 1239 (largest-1-bordered-square)

https://leetcode.com/problems/largest-1-bordered-square

Solution

class Solution:
    def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])

        sum1 = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
        sum2 = [[0 for _ in range(n + 1)] for _ in range(m + 1)]

        for i in range(m):
            for j in range(n):
                sum1[i + 1][j + 1] = grid[i][j] + sum1[i + 1][j]

        for j in range(n):
            for i in range(m):
                sum2[i + 1][j + 1] = grid[i][j] + sum2[i][j + 1]

        k = min(m, n)

        while k > 0:
            for i in range(m - k + 1):
                for j in range(n - k + 1):
                    if sum1[i + 1][j + k] - sum1[i + 1][j] != k:
                        continue

                    if sum1[i + k][j + k] - sum1[i + k][j] != k:
                        continue

                    if sum2[i + k][j + 1] - sum2[i][j + 1] != k:
                        continue

                    if sum2[i + k][j + k] - sum2[i][j + k] != k:
                        continue

                    return k * k

            k -= 1

        return 0