[leetcode] Maximal Square
2015-06-04 21:59
417 查看
From : https://leetcode.com/problems/maximal-square/
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.
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.
public class Solution { public int maximalSquare(char[][] matrix) { if(matrix == null || matrix.length == 0) { return 0; } int max = 0, m = matrix.length, n = matrix[0].length; for(int i=0; i<m && (m-i)*(m-i)>max; ++i) { for(int j=0; j<n && (n-j)*(n-j)>max; j++) { if(matrix[i][j] == '1') { int a = area(matrix, i, j, m, n, max); if(a > max) { max = a; } } } } return max; } private int area(char[][] mt, int sti, int stj, int m, int n, int max) { int i=sti, a=0; int l = n; // minimum length while(i < m) { // boundry int k = i-sti+1; int j = stj; while(j<n && mt[i][j]!='0') { ++j; } if(j-stj < l) { l = j-stj; } // area int ta = l*l; if(k < l) { ta = k*k; } if(ta > a) { a = ta; } // try stop if(k >= l || l*l <= max) { break; } ++i; } return a; } }
class Solution { public: void checkSquare(vector<vector<char>>& matrix, int stRow, int stCol,int rows, int cols, int& max) { int j, i=stRow, col = cols; while(i < rows) { j = stCol; while(j<cols && matrix[i][j]!='0') j++; if((j-stCol)*(j-stCol) <= max) return; if(j-stCol < col) col = j-stCol; if(++i-stRow>col) return; if((i-stRow)*(i-stRow) > max) max = (i-stRow)*(i-stRow); } } int maximalSquare(vector<vector<char>>& matrix) { int max = 0, rows = matrix.size(), cols; for(int i=0; i<rows; i++) { cols = matrix[i].size(); if((rows-i)*(rows-i) <= max || cols*cols <= max) continue; for(int j=0; j<cols; j++) { if((rows-i)*(cols-j) <= max) break; checkSquare(matrix, i, j, rows, cols, max); } } return max; } };
相关文章推荐
- 山一程,水一程,身向榆关那畔行,夜深千帐灯。
- C/C++字符串与字符数组
- 网络通信
- JAVA方法值传递OR引用传递
- 2015/6/4 深圳--存钱罐(存钱网)
- 从哪里开始
- SpeechClassifier API 与端点检测
- P124.45
- 评课-软件工程
- UIImageView 基本用法
- Linux Socket 编程与 TCP/UDP协议流程
- bzoj1044木棍分割
- 新找到一个安装Android SDk的方法-记录
- 系统管理(雏形)
- 《算法导论》读书笔记之图论算法—Dijkstra 算法求最短路径
- YII2_01_简介
- “支付宝”角度看“两个元素互换的中间变量”
- IndexOf、LastIndexOf、Substring的用法
- HttpModule的认识
- css之css设置