Leetcode 764. Largest Plus Sign
思路:动态规划。对于第i行第j列的元素grid[i][j]表示的是这个元素的plus sign的等级,初始化不在mines中的元素对应的grid值为较大值(只要大于N/2即可),在mines中的元素对应的grid值为0。不在mines中的元素,其grid[i][j]=左右上下四个方向最少的连续1的个数(不包括自己)+1。以由左至右为例,假设当前的grid[i][j]已经最优,那么如果(i,j)左侧没有grid[i][j]=0的元素的话,grid[i][j]就要和l取较小值表示当前的最优;如果左侧有grid[i][j]=0的元素,假设是grid[i][k]=0,那么就是取grid[i][j]和j-k的较小值表示当前的最优。最后的最后,取grid[i][j]最大的值作为返回值。
1 class Solution { 2 public int orderOfLargestPlusSign(int N, int[][] mines) { 3 int[][] grid = new int[N][N]; 4 for(int[] m:grid) { 5 Arrays.fill(m, N);//初始化为较大值 6 } 7 for(int[] m:mines) { 8 grid[m[0]][m[1]] = 0; 9 } 10 for(int i = 0; i < N; i++) { 11 for(int j = 0, k = N - 1, l = 0, r = 0, u = 0, d = 0; j < N; j++, k--) { 12 grid[i][j] = Math.min(grid[i][j], l = (grid[i][j] == 0 ? 0 : l + 1));//由左至右 13 grid[i][k] = Math.min(grid[i][k], r = (grid[i][k] == 0 ? 0 : r + 1));//由右至左 14 grid[j][i] = Math.min(grid[j][i], u = (grid[j][i] == 0 ? 0 : u + 1));//由上至下 15 grid[k][i] = Math.min(grid[k][i], d = (grid[k][i] == 0 ? 0 : d + 1));//由下至上 16 } 17 } 18 int res = 0; 19 for(int i = 0; i < N; i++) { 20 for(int j = 0; j < N; j++) { 21 res = Math.max(res, grid[i][j]); 22 } 23 } 24 return res; 25 } 26 }