原題連接在這裏:https://leetcode.com/problems/largest-plus-sign/less
題目:spa
In a 2D grid
from (0, 0) to (N-1, N-1), every cell contains a 1
, except those cells in the given list mines
which are 0
. What is the largest axis-aligned plus sign of 1
s contained in the grid? Return the order of the plus sign. If there is none, return 0.rest
An "axis-aligned plus sign of 1
s of order k" has some center grid[x][y] = 1
along with 4 arms of length k-1
going up, down, left, and right, and made of 1
s. This is demonstrated in the diagrams below. 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 1s.code
Examples of Axis-Aligned Plus Signs of Order k:blog
Order 1: 000 010 000 Order 2: 00000 00100 01110 00100 00000 Order 3: 0000000 0001000 0001000 0111110 0001000 0001000 0000000
Example 1:leetcode
Input: N = 5, mines = [[4, 2]] Output: 2 Explanation: 11111 11111 11111 11111 11011 In the above grid, the largest plus sign can only be order 2. One of them is marked in bold.
Example 2:get
Input: N = 2, mines = [] Output: 1 Explanation: There is no plus sign of order 2, but there is of order 1.
Example 3:it
Input: N = 1, mines = [[0, 0]] Output: 0 Explanation: There is no plus sign, so return 0.
Note:io
N
will be an integer in the range [1, 500]
.mines
will have length at most 5000
.mines[i]
will be length 2 and consist of integers in the range [0, N-1]
.題解:class
For each cell, plus sign is its min of left, right, up and down reach.
We could use brute force. It would take O(N) for each cell and totally O(N^3).
Otherwise, we could iterate each row left to right, calculate farest left reach for each cell. Unless cell is 0, keep accumlate length.
Iterate each row right to left, calculate farest right reach for each cell.
Same for columns to get farest up and down reach.
Get the minimum from farest left, right, up and down reach. Update final result.
Time Complexity: O(N^2).
Space: O(N^2).
AC Java:
1 class Solution { 2 public int orderOfLargestPlusSign(int N, int[][] mines) { 3 if(N <= 0){ 4 return 0; 5 } 6 7 int [][] matrix = new int[N][N]; 8 for(int i = 0; i<N; i++){ 9 Arrays.fill(matrix[i], N); 10 } 11 12 for(int [] mine : mines){ 13 matrix[mine[0]][mine[1]] = 0; 14 } 15 16 for(int i = 0; i<N; i++){ 17 for(int col = 0, l = 0; col<N; col++){ 18 l = matrix[i][col] == 0 ? 0 : l+1; 19 matrix[i][col] = Math.min(matrix[i][col], l); 20 } 21 22 for(int col = N-1, r = 0; col>=0; col--){ 23 r = matrix[i][col] == 0 ? 0 : r+1; 24 matrix[i][col] = Math.min(matrix[i][col], r); 25 } 26 27 for(int row = 0, u = 0; row<N; row++){ 28 u = matrix[row][i] == 0 ? 0 : u+1; 29 matrix[row][i] = Math.min(matrix[row][i], u); 30 } 31 32 for(int row = N-1, d = 0; row>=0; row--){ 33 d = matrix[row][i] == 0 ? 0 : d+1; 34 matrix[row][i] = Math.min(matrix[row][i], d); 35 } 36 } 37 38 int res = 0; 39 for(int i = 0; i<N; i++){ 40 for(int j = 0; j<N; j++){ 41 res = Math.max(res, matrix[i][j]); 42 } 43 } 44 45 return res; 46 } 47 }