zoukankan      html  css  js  c++  java
  • Maximal Square 解答

    Question

    Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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
    

    Return 4.

    Solution

    2-D array. The changing condition is:

    t[i][j] = min(t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1.

     1 public class Solution {
     2     public int maximalSquare(char[][] matrix) {
     3         if (matrix == null || matrix.length < 1)
     4             return 0;
     5         int row = matrix.length, column = matrix[0].length, max = 0;
     6         int[][] dp = new int[row][column];
     7         // Top Row
     8         for (int i = 0; i < column; i++) {
     9             if (matrix[0][i] == '0')
    10                 dp[0][i] = 0;
    11             else
    12                 dp[0][i] = 1;
    13         }
    14         // Left Column
    15         for (int i = 0; i < row; i++) {
    16             if (matrix[i][0] == '0')
    17                 dp[i][0] = 0;
    18             else
    19                 dp[i][0] = 1;
    20         }
    21         // Inside Filling
    22         for (int i = 1; i < row; i++) {
    23             for (int j = 1; j < column; j++) {
    24                 if (matrix[i][j] == '0') {
    25                     dp[i][j] = 0;
    26                 } else {
    27                     int tmp = Math.min(dp[i][j - 1], dp[i - 1][j]);
    28                     dp[i][j] = Math.min(tmp, dp[i - 1][j - 1]) + 1;
    29                 }
    30             }
    31         }
    32         for (int i = 0; i < row; i++) {
    33             for (int j = 0; j < column; j++)
    34                 max = Math.max(max, dp[i][j]);
    35         }
    36         return max * max;
    37     }
    38 }
  • 相关阅读:
    C#线程使用学习
    C# 线程
    C# Lambda表达式与Linq
    C#聚合运算方法
    责任链模式
    代理模式
    享元模式
    门面模式(外观模式)
    桥梁模式
    设计模式-创建型、结构型、行为型之间的区别
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4825162.html
Copyright © 2011-2022 走看看