码迷,mamicode.com
首页 > 其他好文 > 详细

Maximal Square II

时间:2019-12-21 22:24:34      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:sample   highlight   only   public   output   int   最小值   binary   ++i   

Description

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest square which diagonal is all 1 and others is 0.

Only consider the main diagonal situation.

Example

Example 1:

Input:
[[1,0,1,0,0],[1,0,0,1,0],[1,1,0,0,1],[1,0,0,1,0]]
Output:
9
Explanation:
[0,2]->[2,4]

Example 2:

Input:
[[1,0,1,0,1],[1,0,0,1,1],[1,1,1,1,1],[1,0,0,1,0]]
Output:
4
Explanation:
[0,2]->[1,3]
思路:动态规划,u和l数组分别代表左边三角形的最大值和上方三角形的最大值,而f代表对角线到此点的最大长度。
直接三者求最小值转移即可。
public int maxSquare2(int[][] matrix) {
        // write your code here
        int n = matrix.length;
        if (n == 0)
            return 0;

        int m = matrix[0].length;
        if (m == 0)
            return 0;

        int[][] f = new int[n][m];
        int[][] u = new int[n][m];
        int[][] l = new int[n][m];

        int length = 0;
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < m; ++j) {
                if (matrix[i][j] == 0) {
                    f[i][j] = 0;
                    u[i][j] = l[i][j] = 1;
                    if (i > 0)
                        u[i][j] = u[i - 1][j] + 1;
                    if (j > 0)
                        l[i][j] = l[i][j - 1] + 1;
                } else {
                    u[i][j] = l[i][j] = 0;
                    if (i > 0 && j > 0)
                        f[i][j] = Math.min(f[i - 1][j - 1], Math.min(u[i - 1][j], l[i][j - 1])) + 1;
                    else 
                        f[i][j] = 1;
                }
                length = Math.max(length, f[i][j]);
            }
        return length * length;
    }
}

  

Maximal Square II

标签:sample   highlight   only   public   output   int   最小值   binary   ++i   

原文地址:https://www.cnblogs.com/FLAGyuri/p/12078292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!