# LeetCode Maximal Square

157人阅读 评论(0)

Description:

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

Solution:

import java.util.*;

public class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
if (m == 0)
return 0;
int n = matrix[0].length;
int len = Math.min(m, n);

loop: for (int l = 1; l <= len; l++) {
for (int i = 0; i <= m - l; i++) {
for (int j = 0; j <= n - l; j++) {
if (matrix[i][j] == '1' && valid(matrix, i, j, l))
continue loop;
}
}
return (l - 1) * (l - 1);
}
return len * len;
}

boolean valid(char[][] matrix, int a, int b, int len) {
for (int i = a; i < a + len; i++)
for (int j = b; j < b + len; j++)
if (matrix[i][j] != '1')
return false;
return true;
}
}

import java.util.*;

public class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
if (m == 0)
return 0;
int n = matrix[0].length;
int dp[][] = new int[m][n];
int max = 0;

for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (matrix[i][j] == '1') {
dp[i][j] = 1;
max = 1;
}

int maxL = Math.max(m, n);
for (int l = 1; l < maxL; l++) {
for (int i = 0; i < m - l; i++)
for (int j = 0; j < n - l; j++) {
if (dp[i][j] == l && dp[i][j + 1] == l && dp[i + 1][j] == l
&& dp[i + 1][j + 1] == l) {
dp[i][j] = l + 1;
max = dp[i][j];
}
}
}

return max * max;
}
}

import java.util.*;

public class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
if (m == 0)
return 0;
int n = matrix[0].length;
int dp[][] = new int[m][n];
int max = 0;

for (int i = 0; i < m; i++)
if (matrix[i][n - 1] == '1') {
dp[i][n - 1] = 1;
max = 1;
}
for (int j = 0; j < n; j++)
if (matrix[m - 1][j] == '1') {
dp[m - 1][j] = 1;
max = 1;
}

for (int i = m - 2; i >= 0; i--)
for (int j = n - 2; j >= 0; j--)
if (matrix[i][j] == '1') {
dp[i][j] = Math.min(dp[i + 1][j + 1],
Math.min(dp[i + 1][j], dp[i][j + 1])) + 1;
max = Math.max(max, dp[i][j]);
}
return max * max;
}
}

0
0

【套餐】嵌入式Linux C编程基础
【套餐】2017软考系统集成项目——任铄
【套餐】Android 5.x顶级视频课程——李宁
【套餐】深度学习入门视频课程——唐宇迪
【直播】广义线性模型及其应用——李科
【直播】从0到1 区块链的概念到实践
【直播】计算机视觉原理及实战——屈教授
【直播】机器学习之凸优化——马博士
【直播】机器学习&数据挖掘7周实训--韦玮

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：61438次
• 积分：3253
• 等级：
• 排名：第10408名
• 原创：288篇
• 转载：0篇
• 译文：0篇
• 评论：4条
文章分类
阅读排行
最新评论