C++ 全是1的最大方形子矩陣

Maximum size square sub-matrix with all 1s

動畫

#include <bits/stdc++.h>
#define m 5
#define n 5
using namespace std;
int main(){
    ios::sync_with_stdio(0), cin.tie(0);
    int a[m][n] = {{0,1,1,0,1},
                   {1,1,1,1,0},
                   {0,1,1,1,0},
                   {1,1,1,1,0},
                   {0,0,0,0,0}};
    int a2[m][n];
    for(int i=0; i<m; i++)
        a2[i][0] = a[i][0];
    for(int j=0; j<n; j++)
        a2[0][j] = a[0][j];
    for(int i=1; i<m; i++){
        for(int j=1; j<n; j++){
            if(a[i][j] == 1)
                a2[i][j] = min(a[i-1][j],min(a[i][j-1],a[i-1][j-1])) + 1;
            else
                a2[i][j] = 0;
        }
    }
    int max_a2 = a2[0][0], max_i = 0, max_j = 0;
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(a2[i][j] >= max_a2){
                max_a2 = a2[i][j];
                max_i = i;
                max_j = j;
            }
        }
    }
    //a
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++)
            cout << a[i][j]  << ' ';
        cout << '\n';
    }
    cout << '\n';
    //a2
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++)
            cout << a2[i][j]  << ' ';
        cout << '\n';
    }
    cout << '\n';
    //Maximum sub-matrix
    for(int i=max_i; i >= max_i-max_a2; i--){
        for(int j=max_j; j >= max_j-max_a2; j--)
            cout << a[i][j] << ' ';
        cout << '\n';
    }
}
0 1 1 0 1
1 1 1 1 0
0 1 1 1 0
1 1 1 1 0
0 0 0 0 0
0 1 1 0 1
1 1 2 1 0
0 1 2 2 0
1 1 2 2 0
0 0 0 0 0
1 1 1
1 1 1
1 1 1
發佈留言

發佈留言必須填寫的電子郵件地址不會公開。