1139. 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 k = Math.min(m, n); k > 0; --k) {
14             for (int i = 0; i < m - k + 1; ++i) {
15                 for (int j = 0; j < n - k + 1; ++j) {
16                     if (top[i + k - 1][j] >= k && top[i + k - 1][j + k - 1] >= k && left[i][j + k - 1] >= k
17                             && left[i + k - 1][j + k - 1] >= k) {
18                         return k * k;
19                     }
20                 }
21             }
22         }
23         return 0;
24     }
25 }

 

posted @ 2020-02-02 12:44  北叶青藤  阅读(220)  评论(0编辑  收藏  举报