[LeetCode]Largest 1-Bordered Square@Golang

Largest 1-Bordered Square
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn’t exist in the grid.

Example

Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 9

Solution

func largest1BorderedSquare(grid [][]int) int {
    m, n := len(grid), len(grid[0])
    c, r := [101][101]int{}, [101][101]int{}
    
    for i:=1;i<=m;i++{
        for j:=1;j<=n;j++{
            if grid[i-1][j-1]==1 {
                c[i][j] = c[i][j-1] + 1
                r[i][j] = r[i-1][j] + 1
            }
        }
    }
    
    for w:=min(m,n);w>0;w--{
        for i:= 1; i<=m-w+1; i++{
            for j:= 1; j<=n-w+1; j++ {
                if c[i][j+w-1]>=w && 
                c[i+w-1][j+w-1]>=w &&
                r[i+w-1][j]>=w &&
                r[i+w-1][j+w-1]>=w {
                    return w*w
                }
            }
        }
    }
    return 0
}
func min(a,b int)int {
    if a<b{
        return a
    }
    return b
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章