题解 | #边界都是1的最大正方形大小#
边界都是1的最大正方形大小
http://www.nowcoder.com/practice/ac6dce3e0c254c7fab8e72b87e8946fa
import java.util.Scanner; public class Main { /*1、一共N*N个位置,复杂度O(N^2) 2、对于每一个位置,检测是否有边长为1---N的正方形 复杂度O(N) 3、如何检测,复杂度O(1) 时间复杂度为O(n^3) 空间复杂度为O(n^2) * */ public static int getMaxSize(int[][] m) { int[][] right = new int[m.length][m[0].length]; int[][] down = new int[m.length][m[0].length]; setBorderMap(m, right, down); for (int size = Math.min(m.length, m[0].length); size != 0; size--) { if (hasSizeOfBorder(size, right, down)) { return size; } } return 0; } //构建right、down矩阵 public static void setBorderMap(int[][] m, int[][] right, int[][] down) { int r = m.length; int c = m[0].length; if (m[r - 1][c - 1] == 1) { right[r - 1][c - 1] = 1; down[r - 1][c - 1] = 1; } //最后一列初始化 for (int i = r - 2; i != -1; i--) { if (m[i][c - 1] == 1) { right[i][c - 1] = 1; down[i][c - 1] = down[i + 1][c - 1] + 1; } } //最后一行初始化 for (int i = c - 2; i != -1; i--) { if (m[r - 1][i] == 1) { right[r - 1][i] = right[r - 1][i + 1] + 1; down[r - 1][i] = 1; } } for (int i = r - 2; i != -1; i--) { for (int j = c - 2; j != -1; j--) { if (m[i][j] == 1) { right[i][j] = right[i][j + 1] + 1; down[i][j] = down[i + 1][j] + 1; } } } } //判断 public static boolean hasSizeOfBorder(int size, int[][] right, int[][] down) { //左上角的范围 for (int i = 0; i != right.length - size + 1; i++) { for (int j = 0; j != right[0].length - size + 1; j++) { if (right[i][j] >= size && down[i][j] >= size && right[i + size - 1][j] >= size && down[i][j + size - 1] >= size) { return true; } } } return false; } public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int[][]m=new int[n][n]; for (int i = 0; i <n ; i++) { for (int j = 0; j <n ; j++) { m[i][j]=in.nextInt(); } } int res=getMaxSize(m); System.out.println(res); } }