[LeetCode] Largest Plus Sign

764. Largest Plus Sign

You are given an integer n. You have an n x n binary grid grid with all values initially 1’s except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.

Return the order of the largest axis-aligned plus sign of 1’s contained in grid. If there is none, return 0.

An axis-aligned plus sign of 1’s of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1’s. Note that there could be 0’s or 1’s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1’s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int orderOfLargestPlusSign(int n, vector<vector<int>>& mines) {
vector<vector<int>> grid(n, vector<int>(n, 1));
vector<vector<int>> lpsum(n, vector<int>(n, 0));
vector<vector<int>> rpsum(n, vector<int>(n, 0));
vector<vector<int>> upsum(n, vector<int>(n, 0));
vector<vector<int>> bpsum(n, vector<int>(n, 0));
for(auto m : mines)
grid[m[0]][m[1]] = 0;
int res = 0;
for(int i = 0, b = n - 1; i < n; i++, b--) {
for(int l = 0, r = n - 1; l < n; l++, r--) {
if(grid[i][l]) lpsum[i][l] = (1 + (l ? lpsum[i][l-1] : 0));
if(grid[i][r]) rpsum[i][r] = (1 + (r + 1 < n ? rpsum[i][r + 1] : 0));
if(grid[i][l]) upsum[i][l] = (1 + (i ? upsum[i-1][l] : 0));
if(grid[b][l]) bpsum[b][l] = (1 + (b + 1 < n ? bpsum[b + 1][l] : 0));
}
}

for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
res = max(res, min({lpsum[i][j], rpsum[i][j], upsum[i][j], bpsum[i][j]}));
}
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/31/PS/LeetCode/largest-plus-sign/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.