You are given an integer n
that indicates the size of a n x n
binary grid. Initially, every cell in the grid is a 1. You are also given an array mines
where mines[i] = [xi, yi]
indicates that the cell (xi, yi)
receives a 0. This action turns the cell (xi, yi)
into a mine.
You need to find the order of the largest axis-aligned plus sign of 1s contained in the grid after performing these operations. An order of the largest plus sign is defined as the largest integer k
such that there exists a plus sign of order k
with its center in some cell of the grid, which contains only 1s. A plus sign of order k
has a center cell (r, c)
with the following property that must be true for all 0 <= i < k
:
(r, c+i)
(r, c-i)
(r+i, c)
(r-i, c)
Return an integer that represents the order of the largest plus sign.
n
?mines
array have?0
if there is no valid plus sign?mines
is empty and there are no 0s in the grid?mines
array.(i, j)
, compute the minimum value from the four auxiliary arrays, which gives the maximum k
for the plus sign centered at (i, j)
.def orderOfLargestPlusSign(n, mines):
if n == 0:
return 0
# Initialize the grid
grid = [[1] * n for _ in range(n)]
for mine in mines:
grid[mine[0]][mine[1]] = 0
left = [[0] * n for _ in range(n)]
right = [[0] * n for _ in range(n)]
top = [[0] * n for _ in range(n)]
bottom = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
left[i][j] = left[i][j-1] + 1 if j > 0 else 1
top[i][j] = top[i-1][j] + 1 if i > 0 else 1
for i in range(n-1, -1, -1):
for j in range(n-1, -1, -1):
if grid[i][j] == 1:
right[i][j] = right[i][j+1] + 1 if j < n-1 else 1
bottom[i][j] = bottom[i+1][j] + 1 if i < n-1 else 1
max_order = 0
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
order = min(left[i][j], right[i][j], top[i][j], bottom[i][j])
max_order = max(max_order, order)
return max_order
Overall, the time complexity is O(n^2). This is efficient given that we need to consider every cell in the grid and the computations for each cell are constant time operations.
n
is 0
, the function returns 0
as there’s no grid.mines
covers the entire grid, the function returns 0
since no 1-cell exists.mines
is empty, the order of the largest plus sign will be n//2 + 1
.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?