LeetCode1139. 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 1:

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

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

Constraints:

1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j] is 0 or 1

二、题解

class Solution {
public:
    int largest1BorderedSquare(vector<vector<int>>& grid) {
        int n = grid.size(),m = grid[0].size();
        build(grid,n,m);
        if(sum(grid,0,0,n-1,m-1) == 0) return 0;
        int res = 1;
        for(int a = 0;a < n;a++){
            for(int b = 0;b < m;b++){
                for(int c = a + res,d = b + res,k = res + 1;c < n && d < m;c++,d++,k++){
                    if(sum(grid,a,b,c,d) - sum(grid,a+1,b+1,c-1,d-1) == (k-1) << 2) res = k;
                }
            }
        }
        return res * res;
    }
    void build(vector<vector<int>>& g,int n,int m){
        for(int i = 0;i < n;i++){
            for(int j = 0;j < m;j++){
                g[i][j] += get(g,i-1,j) + get(g,i,j-1) - get(g,i-1,j-1);
            }
        }
    }
    int sum(vector<vector<int>>& g,int a,int b,int c,int d){
        return a > c ? 0 : (g[c][d] - get(g, c, b - 1) - get(g, a - 1, d) + get(g, a - 1, b - 1));
    }
    int get(vector<vector<int>>& g,int i,int j){
        return (i < 0 || j < 0) ? 0 : g[i][j];
    }
};

你可能感兴趣的:(算法,数据结构,leetcode,c++)