其他分享
首页 > 其他分享> > Largest 1-Bordered Square

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
 1 class Solution {
 2     public int largest1BorderedSquare(int[][] A) {
 3         int m = A.length, n = A[0].length;
 4         int[][] left = new int[m][n], top = new int[m][n];
 5         for (int i = 0; i < m; ++i) {
 6             for (int j = 0; j < n; ++j) {
 7                 if (A[i][j] > 0) {
 8                     left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1;
 9                     top[i][j] = i > 0  ? top[i - 1][j] + 1 : 1;
10                 }
11             }
12         }
13         for (int l = Math.min(m, n); l > 0; --l)
14             for (int i = 0; i < m - l + 1; ++i)
15                 for (int j = 0; j < n - l + 1; ++j)
16                     if (top[i + l - 1][j] >= l &&
17                             top[i + l - 1][j + l - 1] >= l &&
18                             left[i][j + l - 1] >= l &&
19                             left[i + l - 1][j + l - 1] >= l)
20                         return l * l;
21         return 0;
22     }
23 }

 

标签:Square,return,int,top,Bordered,++,grid,Largest,left
来源: https://www.cnblogs.com/beiyeqingteng/p/12251756.html