/** * Given an m x n binary matrix filled with 0's and 1's, * find the largest square containing only 1's and return its area. * <p> * Example 1: * Input: matrix = [ * ["1","0","1","0","0"], * ["1","0","1","1","1"], * ["1","1","1","1","1"], * ["1","0","0","1","0"] * ] * Output: 4 * <p> * Example 2: * Input: matrix = [ * ["0","1"], * ["1","0"] * ] * Output: 1 * <p> * Example 3: * Input: matrix = [ * ["0"] * ] * Output: 0 */public class Lesson221 { static class Counter { void test() { Random random = new Random(); int rows = random.nextInt(10) + 1; int cols = rows; char[][] matrix = new char[cols][rows]; for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { (matrix[i][j]) = Character.forDigit((int) (Math.random() + 0.5), 10); } } StringBuilder stringBuilder = new StringBuilder("[\n"); for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { stringBuilder.append(matrix[i][j]); if (j < rows) { stringBuilder.append(","); } } if (i < cols) { stringBuilder.append("\n"); } } stringBuilder.append("]"); System.out.println(stringBuilder); int result = new Solution().maximalSquare(matrix); System.out.println(result); } } // 暴力破解 private static class Solution { public int maximalSquare(char[][] matrix) { int rows = matrix.length; int cols = rows > 0 ? matrix[0].length : 0; int maxsqlen = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (matrix[i][j] == '1') { int sqlen = 1; boolean flag = true; while (sqlen + i < rows && sqlen + j < cols && flag) { for (int k = j; k <= sqlen + j; k++) { if (matrix[i + sqlen][k] == '0') { flag = false; break; } } for (int k = i; k <= sqlen + i; k++) { if (matrix[k][j + sqlen] == '0') { flag = false; break; } } if (flag) sqlen++; } if (maxsqlen < sqlen) { maxsqlen = sqlen; } } } } return maxsqlen * maxsqlen; } } public static void main(String[] args) { Counter counter = new Counter(); for (int i = 0; i < 10; i++) { counter.test(); System.out.println("----------------------"); } }}