leetcode:85. Maximal Rectangle

Dear 丶 2022-07-15 23:56 247阅读 0赞

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

  1. import java.util.Arrays;
  2. public class Solution{
  3. public static void main(String[] args) {
  4. // TODO Auto-generated method stub
  5. Solution s = new Solution();
  6. char[][] matrix = new char[][] { { '1', '0', '1', '0', '0' }, { '1', '0', '1', '1', '1' },
  7. { '1', '1', '1', '1', '1' }, { '1', '0', '0', '1', '0' } };
  8. matrix = new char[][] { "10100".toCharArray(), "10111".toCharArray(), "11111".toCharArray(),
  9. "10010".toCharArray() };
  10. matrix = new char[][] { "01101".toCharArray(), "11010".toCharArray(), "01110".toCharArray(),
  11. "11110".toCharArray(), "11111".toCharArray(), "00000".toCharArray() };
  12. int ans = s.maximalSquare(matrix);
  13. System.out.println(ans);
  14. }
  15. public int maximalSquare(char[][] matrix) {
  16. if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
  17. return 0;
  18. }
  19. // output(matrix);
  20. int ans = 0;
  21. int row = matrix.length;
  22. int col = matrix[0].length;
  23. int[][] dp = new int[row][col];
  24. for (int i = 0; i < row; ++i) {
  25. for (int j = 0; j < col; ++j) {
  26. if ('0' == matrix[i][j]) {
  27. dp[i][j] = 0;
  28. continue;
  29. }
  30. dp[i][j] = 1;
  31. int min = Math.min(inBorad(i - 1, j, dp), inBorad(i, j - 1, dp));
  32. while(min > 0){
  33. if(matrix[i - min][j - min] == '1'){
  34. dp[i][j] = min + dp[i][j];
  35. break;
  36. }
  37. -- min;
  38. }
  39. if (dp[i][j] > ans) {
  40. ans = dp[i][j];
  41. }
  42. }
  43. // output(dp);
  44. }
  45. return ans * ans;
  46. }
  47. void output(int[][] dp) {
  48. for (int[] d : dp)
  49. System.out.println(Arrays.toString(d));
  50. System.out.println("===================================");
  51. }
  52. void output(char[][] dp) {
  53. for (char[] d : dp)
  54. System.out.println(Arrays.toString(d));
  55. System.out.println("===================================");
  56. }
  57. public int inBorad(int x, int y, int[][] dp) {
  58. return x >= 0 && y >= 0 ? dp[x][y] : 0;
  59. }
  60. }
  61. /**
  62. *
  63. * 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
  64. *
  65. */

发表评论

表情:
评论列表 (有 0 条评论,247人围观)

还没有评论,来说两句吧...

相关阅读