LeetCode 1139:最大的以 1 为边界的正方形(Largest 1-Bordered Square)解法汇总

文章目录

  • Solution

更多LeetCode题解

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

Solution

对于每一种可能大小的边长进行穷举即可。

class Solution {
public:
    int largest1BorderedSquare(vector<vector<int>>& grid) {
        int res = 0;
        for(int k=0;k<min(grid.size(), grid[0].size());k++){
            for(int i=0;i<grid.size()-k;i++){
                for(int j=0;j<grid[0].size()-k;j++){
                    if(isValidSquare(grid,i,j,k)){
                        res = (k+1)*(k+1);
                    }
                }
            }
        }
        return res;
    }
    bool isValidSquare(vector<vector<int>>& grid, int x, int y, int w){
        for(int i=x;i<=x+w;i++){
            if(!grid[i][y]){
                return false;
            }
        }
        for(int i=x;i<=x+w;i++){
            if(!grid[i][y+w]){
                return false;
            }
        }
        for(int i=y;i<=y+w;i++){
            if(!grid[x][i]){
                return false;
            }
        }
        for(int i=y;i<=y+w;i++){
            if(!grid[x+w][i]){
                return false;
            }
        }
        return true;
    }
};

你可能感兴趣的:(LeetCode,LeetCode刷题题解记录)