[LeetCode] 01矩阵中最大正方形 Maximal Square
2015-08-04 03:48
417 查看
相关问题1:[LeetCode] Find max subsquare whose
border values are all 1
相关问题2:[LeetCode] 01矩阵中最大矩形 Maximal Rectangle
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:
Return 4.
思路:
假设给定是矩阵是 M ,可以构建一个大小一样的辅助矩阵S,具体构建规则如下:
这样一来,S[ i ] [ j ] 就代表了以 M[ i ] [ j ] 为右下角的、最大的、全1 的 正方形的边长。
具体代码如下:
border values are all 1
相关问题2:[LeetCode] 01矩阵中最大矩形 Maximal Rectangle
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.
思路:
假设给定是矩阵是 M ,可以构建一个大小一样的辅助矩阵S,具体构建规则如下:
1) Construct a sum matrix S[R][C] for the given M[R][C]. a) Copy first row and first columns as it is from M[][] to S[][] b) For other entries, use following expressions to construct S[][] If M[i][j] is 1 then S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1 Else /*If M[i][j] is 0*/ S[i][j] = 0 2) Find the maximum entry in S[R][C] 3) Using the value and coordinates of maximum entry in S[i], print sub-matrix of M[][]
这样一来,S[ i ] [ j ] 就代表了以 M[ i ] [ j ] 为右下角的、最大的、全1 的 正方形的边长。
具体代码如下:
class Solution { public: int maximalSquare(vector<vector<char>>& M) { int R = M.size(); if(R==0) return 0; int C = M[0].size(); if(C==0) return 0; int i,j; vector<vector<int>> S(R, vector<int>(C, 0) ); int max_of_s, max_i, max_j; for(i = 0; i < R; i++) S[i][0] = M[i][0] - '0'; for(j = 0; j < C; j++) S[0][j] = M[0][j] - '0'; for(i = 1; i < R; i++) { for(j = 1; j < C; j++) { if(M[i][j] == '1') S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1; else S[i][j] = 0; } } max_of_s = S[0][0]; max_i = 0; max_j = 0; for(i = 0; i < R; i++) { for(j = 0; j < C; j++) { if(max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } return max_of_s*max_of_s; } /* Function to get minimum of three values */ int min(int a, int b, int c) { int m = a; if (m > b) m = b; if (m > c) m = c; return m; } };
相关文章推荐
- poj 2481 Cows(树状数组)
- Why Reflection is slowly?(Trail: The Reflection API)
- codeforce #126Div2 200A Cinema 【优化暴力枚举】
- Why Reflection is slowly?(Trail: The Reflection API)
- 黑马程序员———反射机制
- 踢毽子问题
- HDU 4008 Parent and son (数据结构)
- 【爱笑话7.0版】笑话两万篇,免费阅读,绝无广告
- 【爱笑话7.0版】笑话两万篇,免费阅读,绝无广告
- java String 中的==null、length()==0、=="" 理解
- [leetCode] Different Ways to Add Parentheses
- Ubuntu14.04配置使用无线连接WiFi热点
- java.net.ServerSocket详解
- MySQL调优 —— Using temporary
- 运算符和条件语句
- 【进展】2015.08.04 增加 SEMAPHORE 释放功能,增加MUTEX权限判断,非Onwer任务不能解锁
- PHP的正则
- 可合并堆。。。BZOJ1078
- 活用scanf
- warning C4819: 该文件包含不能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 格式以防止数据丢失