Leetcode 764. Largest Plus Sign
You are given an integer n
representing an n x n
grid containing only 1
’s and 0
’s. You are also given an array mines
where mines[i] = [xi, yi]
represents the position (xi, yi)
of a mine on the grid. Return the order of the largest axis-aligned plus sign of 1
’s contained in the grid. If there is none, return 0
.
An “axis-aligned plus sign of 1’s of order k” has some center cell (r, c)
such that:
k
consecutive 1
’s on the up, down, left, and right of (r, c)
, and the center is also 1
.2k - 1
cells of 1
’s, including the center cell.n = 5, mines = [[4, 2]]
Output: 2
Explanation:
11111
11111
11111
11111
11011
In the above grid, the largest plus sign can be formed of order 2, where the center of the plus is at position (1, 2).
n
be 0 or 1?
n * n
mines, and they can be located anywhere on the grid.n x n
grid filled with 1
s. Then, place mines (0
s) in the grid as specified by the mines
array.1
s up to that cell in four directions (left, right, up, down).public class Solution {
public int orderOfLargestPlusSign(int n, int[][] mines) {
int[][] grid = new int[n][n];
// Fill grid with all 1s
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = 1;
}
}
// Place mines
for (int[] mine : mines) {
grid[mine[0]][mine[1]] = 0;
}
int[][] left = new int[n][n];
int[][] right = new int[n][n];
int[][] up = new int[n][n];
int[][] down = new int[n][n];
// Fill the auxiliary grids
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
left[i][j] = (j > 0) ? left[i][j - 1] + 1 : 1;
up[i][j] = (i > 0) ? up[i - 1][j] + 1 : 1;
}
}
}
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
if (grid[i][j] == 1) {
right[i][j] = (j < n - 1) ? right[i][j + 1] + 1 : 1;
down[i][j] = (i < n - 1) ? down[i + 1][j] + 1 : 1;
}
}
}
// Calculate the largest plus sign order
int maxOrder = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int order = Math.min(Math.min(left[i][j], right[i][j]),
Math.min(up[i][j], down[i][j]));
maxOrder = Math.max(maxOrder, order);
}
}
return maxOrder;
}
}
The space complexity is also O(n^2) because of the four auxiliary grids.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?