[LeetCode] Maximal Square
2015-06-03 11:54
281 查看
Well, this problemdesires for the use of dynamic programming. They key to any DP problemis to come up with the state equation. In this problem, we define the state to be the maximal size of the square that can be achieved at point
Now let's try to come up with the formula for
First, it is obvious that for the topmost row (
Let's move to the more general case for
Now we are almost done. The only unsolved case is
Suppose
Now you are near the solution. In fact,
Taking all these together, we have the following state equations.
For
Putting theminto codes, and maintain a variable
Now let's try to optimize the above solution. As can be seen, each time when we update
As can be seen, line 21 of the above involves vector copying, which is a little unnecessary. We can simply maintain two points to the two vectors and just write and swap using the pointers, as in the following code.
Now the solution is finished? In fact, it can still be optimized! In fact, we need not maintain two vectors and one is enough. The idea is that we maintain two vectors simply to recover
Well, someone even suggest not to use the pre variable and simply obtain the information fromthe matrix, which gives the following code.
(i, j), denoted as
P[i][j]. Remember that we usesize instead of square as the state (
square = size^2).
Now let's try to come up with the formula for
P[i][j].
First, it is obvious that for the topmost row (
i = 0) and the leftmost column (
j = 0),
S[i][j] = matrix[i][j]. This is easily understood. Let's suppose that the topmost row of
matrixis like
[1, 0, 0, 1]. Then we can immediately know that the first and last point can be a square of size
1while the two middle points cannot make any square, giving a size of
0. Thus,
P = [1, 0, 0, 1], which is the same as
matrix. The case is similar for the leftmost column. Till now, the boundary conditions of this DP problemare solved.
Let's move to the more general case for
P[i][j]in which
i > 0and
j > 0. First of all, let's see another simple case in which
matrix[i][j] = 0. It is obvious that
P[i][j] = 0too. Why? Well, since
matrix[i][j] = 0, no square will contain
matrix[i][j], according to our definition of
P[i][j],
P[i][j]is also
0.
Now we are almost done. The only unsolved case is
matrix[i][j] = 1. Let's see an example.
Suppose
matrix = [[0, 1], [1, 1]], it is obvious that
P[0][0] = 0, P[0][1] = P[1][0] = 1, what about
P[1][1]? Well, to give a square of size larger than
1in
P[1][1], all of its three neighbors (left, up, left-up) should be non-zero, right? In this case, the left-up neighbor
P[0][0] = 0, so
P[1][1]can only be 1, which means that it contains the square of itself.
Now you are near the solution. In fact,
P[i][j] = min(P[i - 1][j], P[i][j - 1], P[i - 1][j - 1]) + 1in this case.
Taking all these together, we have the following state equations.
P[0][j] = matrix[0][j](topmost row);
P[i][0] = matrix[i][0](leftmost column);
For
i > 0and
j > 0: if
matrix[i][j] = 0,
P[i][j] = 0; if
matrix[i][j] = 1,
P[i][j] = min(P[i - 1][j], P[i][j - 1], P[i - 1][j - 1]) + 1.
Putting theminto codes, and maintain a variable
maxsizeto record the maximumsize of the square we have seen, we have the following (unoptimized) solution.
int maximalSquare(vector<vector<char>>& matrix) { int m= matrix.size(); if (!m) return 0; int n = matrix[0].size(); vector<vector<int> > size(m, vector<int>(n, 0)); int maxsize = 0; for (int j = 0; j < n; j++) { size[0][j] = matrix[0][j] - '0'; maxsize = max(maxsize, size[0][j]); } for (int i = 1; i < m; i++) { size[i][0] = matrix[i][0] - '0'; maxsize = max(maxsize, size[i][0]); } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if (matrix[i][j] == '1') { size[i][j] = min(size[i - 1][j - 1], min(size[i - 1][j], size[i][j - 1])) + 1; maxsize = max(maxsize, size[i][j]); } } } return maxsize * maxsize; }
Now let's try to optimize the above solution. As can be seen, each time when we update
size[i][j], we only need
size[i][j - 1], size[i - 1][j - 1](at the previous left column) and
size[i - 1][j](at the current column). So we do not need to maintain the full
m*nmatrix. In fact, keeping two columns is enough. Now we have the following optimized solution.
int maximalSquare(vector<vector<char>>& matrix) { int m= matrix.size(); if (!m) return 0; int n = matrix[0].size(); vector<int> pre(m, 0); vector<int> cur(m, 0); int maxsize = 0; for (int i = 0; i < m; i++) { pre[i] = matrix[i][0] - '0'; maxsize = max(maxsize, pre[i]); } for (int j = 1; j < n; j++) { cur[0] = matrix[0][j] - '0'; maxsize = max(maxsize, cur[0]); for (int i = 1; i < m; i++) { if (matrix[i][j] == '1') { cur[i] = min(cur[i - 1], min(pre[i - 1], pre[i])) + 1; maxsize = max(maxsize, cur[i]); } } pre = cur; fill(cur.begin(), cur.end(), 0); } return maxsize * maxsize; }
As can be seen, line 21 of the above involves vector copying, which is a little unnecessary. We can simply maintain two points to the two vectors and just write and swap using the pointers, as in the following code.
int maximalSquare(vector<vector<char>>& matrix) { if (matrix.empty()) return 0; int m= matrix.size(), n = matrix[0].size(); vector<int> pre(m, 0), cur(m, 0); auto ppre = &pre, pcur = &cur; int maxsize = 0; for (int i = 0; i < m; i++) { (*ppre)[i] = matrix[i][0] - '0'; maxsize = max(maxsize, pre[i]); } for (int j = 1; j < n; j++) { (*pcur)[0] = matrix[0][j] - '0'; maxsize = max(maxsize, (*pcur)[0]); for (int i = 1; i < m; i++) { if (matrix[i][j] == '1') { (*pcur)[i] = min((*pcur)[i - 1], min((*ppre)[i - 1], (*ppre)[i])) + 1; maxsize = max(maxsize, (*pcur)[i]); } } swap(ppre, pcur); fill((*pcur).begin(), (*pcur).end(), 0); } return maxsize * maxsize; }
Now the solution is finished? In fact, it can still be optimized! In fact, we need not maintain two vectors and one is enough. The idea is that we maintain two vectors simply to recover
pre[i - 1]and this can stored in a single variable, thus eliminating the need for a full vector. Moreover, in the code above, we distinguish between the
0-th row and other rows since the
0-th row has no row above it. In fact, we can make all the
mrows the same by padding a
0row on the top. Finally, we will have the following short code :) If you find it hard to understand, try to run it using your pen and paper and notice how it realizes what the two-vector solution does using only one vector.
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty()) return 0;
int m= matrix.size(), n = matrix[0].size();
vector<int> dp(m+ 1, 0);
int maxsize = 0, pre = 0;
for (int j = 0; j < n; j++) {
for (int i = 1; i <= m; i++) {
int temp = dp[i];
if (matrix[i - 1][j] == '1') {
dp[i] = min(dp[i], min(dp[i - 1], pre)) + 1;
maxsize = max(maxsize, dp[i]);
}
else dp[i] = 0;
pre = temp;
}
}
return maxsize * maxsize;
}
Well, someone even suggest not to use the pre variable and simply obtain the information fromthe matrix, which gives the following code.
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty()) return 0;
int m= matrix.size(), n = matrix[0].size();
vector<int> dp(m+ 1, 0);
int maxsize = 0;
for (int j = 0; j < n; j++) {
for (int i = 1; i <= m; i++) {
if (matrix[i - 1][j] == '1') {
int k = min(dp[i], dp[i - 1]);
dp[i] = matrix[i - k - 1][j - k] == '1' ? k + 1 : k;
maxsize = max(maxsize, dp[i]);
}
else dp[i] = 0;
}
}
return maxsize * maxsize;
}
相关文章推荐
- HTML5 web应用打包成android应用
- 第四章 fragment
- HTML/CSS学习笔记
- shell脚本中echo显示内容带颜色 【常用】
- 开通csdn博客。记录自己点滴成长
- 理解Golang包导入
- Android的HttpURLConnection
- SQL 最日期
- 鉴权加密
- SIM(USIM)卡中的数据和2G/3G网络的鉴权
- mfc static,checkbox,groupbox,redio 控件透明
- android preference 中entries和entryValues
- linux su和sudo命令的区别
- 移动端重构图片文字的水平垂直居中
- 如何显示和隐藏顶部的菜单
- 注意Android里TextView控件的一个小坑,用android:theme来设置样式时动态载入的layout会丢失该样式
- php 中英文字符串截取,字符串长度
- Python实现Windows上气泡提醒效果的方法
- Error parsing DDL for `por`.`info`
- 1. C#数据结构与算法 -- 排序(插入,冒泡,希尔,快速,选择)