算法题 |
算法刷题专栏 | 面试必备算法 | 面试高频算法
越难的东西,越要努力坚持,因为它具有很高的价值,算法就是这样✨
作者简介:硕风和炜,CSDN-Java领域新星创作者,保研|国家奖学金|高中学习JAVA|大学完善JAVA开发技术栈|面试刷题|面经八股文|经验分享|好用的网站工具分享
恭喜你发现一枚宝藏博主,赶快收入囊中吧
人生如棋,我愿为卒,行动虽慢,可谁曾见我后退一步?
算法题 |
在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。
示例:
输入:matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
输出:4
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] 为 ‘0’ 或 ‘1’
class Solution {
int m;
int n;
int max = 0;
public int maximalSquare(char[][] matrix) {
m = matrix.length;
n = matrix[0].length;
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
if (matrix[i][j] == '1') {
max = Math. max(max, process(matrix, i, j));
}
}
}
return max*max;
}
private int process(char[][] matrix, int row, int col) {
if (row >= m || col >= n || matrix[row][col] == '0') {
return 0;
}
int down = process(matrix, row+1, col);
int right = process(matrix, row, col+1);
int rightDown = process(matrix, row+1, col+1);
return 1 + Math.min(down, Math.min(right,rightDown));
}
}
时间超限,是我们期待的结果!!!
class Solution {
int m;
int n;
int[][] dp;
int max = 0;
public int maximalSquare(char[][] matrix) {
m = matrix.length;
n = matrix[0].length;
dp=new int[m][n];
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
if (matrix[i][j] == '1') {
max = Math. max(max, process(matrix, i, j));
}
}
}
return max*max;
}
private int process(char[][] matrix, int row, int col) {
if (row >= m || col >= n || matrix[row][col] == '0') {
return 0;
}
if(dp[row][col]!=0) return dp[row][col];
int down = process(matrix, row+1, col);
int right = process(matrix, row, col+1);
int rightDown = process(matrix, row+1, col+1);
return dp[row][col]=1 + Math.min(down, Math.min(right,rightDown));
}
}
class Solution {
int m;
int n;
int[][] dp;
int max = 0;
public int maximalSquare(char[][] matrix) {
m = matrix.length;
n = matrix[0].length;
dp=new int[m+1][n+1];
for (int row=m-1; row>=0; row--) {
for (int col=n-1; col>=0; col--) {
if (matrix[row][col] == '1') {
int botttom = dp[row+1][col];
int right = dp[row][col+1];
int rightBottom = dp[row+1][col+1];
dp[row][col] = 1 + Math.min(botttom, Math.min(right,rightBottom));
max = Math. max(max, dp[row][col]);
}
}
}
return max*max;
}
}
学完这道题目,你亲自动手试试能不能解决这道题目呢?
最后,我想和大家分享一句一直激励我的座右铭,希望可以与大家共勉! |