1. /**
    2. * Given an m x n binary matrix filled with 0's and 1's,
    3. * find the largest square containing only 1's and return its area.
    4. * <p>
    5. * Example 1:
    6. * Input: matrix = [
    7. * ["1","0","1","0","0"],
    8. * ["1","0","1","1","1"],
    9. * ["1","1","1","1","1"],
    10. * ["1","0","0","1","0"]
    11. * ]
    12. * Output: 4
    13. * <p>
    14. * Example 2:
    15. * Input: matrix = [
    16. * ["0","1"],
    17. * ["1","0"]
    18. * ]
    19. * Output: 1
    20. * <p>
    21. * Example 3:
    22. * Input: matrix = [
    23. * ["0"]
    24. * ]
    25. * Output: 0
    26. */
    27. public class Lesson221 {
    28. static class Counter {
    29. void test() {
    30. Random random = new Random();
    31. int rows = random.nextInt(10) + 1;
    32. int cols = rows;
    33. char[][] matrix = new char[cols][rows];
    34. for (int i = 0; i < cols; i++) {
    35. for (int j = 0; j < rows; j++) {
    36. (matrix[i][j]) = Character.forDigit((int) (Math.random() + 0.5), 10);
    37. }
    38. }
    39. StringBuilder stringBuilder = new StringBuilder("[\n");
    40. for (int i = 0; i < cols; i++) {
    41. for (int j = 0; j < rows; j++) {
    42. stringBuilder.append(matrix[i][j]);
    43. if (j < rows) {
    44. stringBuilder.append(",");
    45. }
    46. }
    47. if (i < cols) {
    48. stringBuilder.append("\n");
    49. }
    50. }
    51. stringBuilder.append("]");
    52. System.out.println(stringBuilder);
    53. int result = new Solution().maximalSquare(matrix);
    54. System.out.println(result);
    55. }
    56. }
    57. // 暴力破解
    58. private static class Solution {
    59. public int maximalSquare(char[][] matrix) {
    60. int rows = matrix.length;
    61. int cols = rows > 0 ? matrix[0].length : 0;
    62. int maxsqlen = 0;
    63. for (int i = 0; i < rows; i++) {
    64. for (int j = 0; j < cols; j++) {
    65. if (matrix[i][j] == '1') {
    66. int sqlen = 1;
    67. boolean flag = true;
    68. while (sqlen + i < rows && sqlen + j < cols && flag) {
    69. for (int k = j; k <= sqlen + j; k++) {
    70. if (matrix[i + sqlen][k] == '0') {
    71. flag = false;
    72. break;
    73. }
    74. }
    75. for (int k = i; k <= sqlen + i; k++) {
    76. if (matrix[k][j + sqlen] == '0') {
    77. flag = false;
    78. break;
    79. }
    80. }
    81. if (flag)
    82. sqlen++;
    83. }
    84. if (maxsqlen < sqlen) {
    85. maxsqlen = sqlen;
    86. }
    87. }
    88. }
    89. }
    90. return maxsqlen * maxsqlen;
    91. }
    92. }
    93. public static void main(String[] args) {
    94. Counter counter = new Counter();
    95. for (int i = 0; i < 10; i++) {
    96. counter.test();
    97. System.out.println("----------------------");
    98. }
    99. }
    100. }