Skip to content

Commit 23638c8

Browse files
max sub square with all 1s
1 parent 1b4bcaa commit 23638c8

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Problem: Given a binary matrix, find out the maximum size square sub-matrix with all 1s.
3+
*/
4+
5+
#include <string>
6+
#include <iostream>
7+
#include <vector>
8+
using namespace std;
9+
10+
int min(int x,int y,int z){
11+
return x<((y<z)?y:z)?x:((y<z)?y:z);
12+
}
13+
14+
15+
int maxSquare(vector< vector<int> > &matrix,int row,int col) {
16+
vector< vector<int> > temp(row, vector<int>(col, 0));
17+
int max = 0;
18+
for(int k=0;k<matrix.size();k++)
19+
{
20+
temp[k][0]=matrix[k][0];
21+
if(temp[k][0]>max)
22+
max=temp[k][0];
23+
}
24+
for(int k=0;k<matrix[0].size();k++)
25+
{
26+
temp[0][k]=matrix[0][k];
27+
if(temp[0][k]>max)
28+
max=temp[k][0];
29+
}
30+
for(int r=1;r<matrix.size();r++){
31+
for(int c=1;c<matrix[r].size();c++){
32+
if(matrix[r][c]==1){
33+
temp[r][c]=min(temp[r][c-1],temp[r-1][c-1],temp[r-1][c])+1;
34+
if(temp[r][c]>max)
35+
max=temp[r][c];
36+
}
37+
}
38+
}
39+
return max;
40+
}
41+
42+
int main(){
43+
int row,col;
44+
cin>>row>>col;
45+
vector< vector<int> > matrix(row, vector<int>(col, 0));
46+
//input for the matrix
47+
for(int r=0;r<matrix.size();r++){
48+
for(int c=0;c<matrix[r].size();c++){
49+
cin>>matrix[r][c];
50+
}
51+
}
52+
int maxSubSquare=maxSquare(matrix,row,col);
53+
cout<<"Max Sub Square: "<<maxSubSquare<<" x "<<maxSubSquare<<endl;
54+
}

0 commit comments

Comments
 (0)