1. 程式人生 > 其它 >LeetCode1139. 最大的以 1 為邊界的正方形 [Medium]

LeetCode1139. 最大的以 1 為邊界的正方形 [Medium]

技術標籤:leetcode

1139. Largest 1-Bordered Square

Given a 2D grid of 0 s and 1 s, return the number of elements in the largest square subgrid that has all 1 s 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

題目:給你一個由若干 01 組成的二維網格 grid ,請你找出邊界全部由 1 組成的最大 正方形 子網格,並返回該子網格中的元素數量。如果不存在,則返回 0

思路:參考linkhorver 分別為網格水平和垂直方向的輔助陣列(記錄連續1的個數)。

那麼從右下角開始,為了組成正方形,首先短邊由 min(hor[i][j], ver[i][j]) 決定(右下邊),同時要判斷另外兩條邊(左上邊)是否滿足這個長度。

工程程式碼下載

class Solution {
public:
    int largest1BorderedSquare(vector<vector<int>>& grid) {
        int res = 0;
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> hor(m, vector<int>(n)), ver(m, vector<int>(n));
        for(int i = 0;
i < m; ++i){ for(int j = 0; j < n; ++j){ if(grid[i][j] == 1){ hor[i][j] = i == 0 ? 1 : hor[i-1][j] + 1; ver[i][j] = j == 0 ? 1 : ver[i][j-1] + 1; } } } for(int i = m-1; i >= 0; --i){ for(int j = n-1; j >= 0; --j){ int small = min(hor[i][j], ver[i][j]); while(small > res){ if(hor[i][j-small+1] >= small && ver[i-small+1][j] >= small) res = small; --small; } } } return res * res; } };