1720C - Corners - CodeForces Solution


greedy implementation

Please click on ads to support us..

Python Code:

t= int(input())

for i in range(t):
    n, m= [int(x) for x in input().split()]
    d= [list(map(int, input())) for x in range(n)]

    c= sum(sum(r) for r in d)
    perfect= False

    if (c == n*m):
        print(c-2)
    elif (c == 0):
        print(0)
    else:
        for p in range(n-1):
            for q in range(m-1):
                s= d[p][q] + d[p][q+1] + d[p+1][q] + d[p+1][q+1]
                if (s <= 2):
                    perfect= True
                    break
            if perfect: break

        print(c if perfect else c-1)

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define mp make_pair

const int N=2e5+5;
const int mod=1e9+7;
#include <vector>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <map>
#include <set>
#include <cmath>
#include <array>






void solve(){

int n,m;
cin>>n>>m;

int cnt=0;
int a[n][m];

for(int i=0;i<n;i++){
    string s;
    cin>>s;
for(int j=0;j<m;j++){
    
    a[i][j]=s[j]-'0';
    cnt=cnt+a[i][j];
    
}

}

if(cnt==0)
{
    cout<<"0"<<endl;
    return;
    
}


int mini=INT_MAX;

for(int i=0;i<n-1;i++){
    for(int j=0;j<m-1;j++){
        int t=a[i][j]+a[i+1][j]+a[i][j+1]+a[i+1][j+1];
        
        if(t==0)continue;
        
        mini=min(t,mini);
    }
}

if(mini==1||mini==2){
    cout<<cnt<<endl;
}
else if(mini==3){
     cout<<cnt-1<<endl;
}
else{
     cout<<cnt-2<<endl;
}





}


int32_t main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int T;
    cin>>T;
    
    
    while(T--){
        solve();
    }
   // solve();
}


Comments

Submit
0 Comments
More Questions

1475E - Advertising Agency
1345B - Card Constructions
1077B - Disturbed People
653A - Bear and Three Balls
794A - Bank Robbery
157A - Game Outcome
3B - Lorry
1392A - Omkar and Password
489A - SwapSort
932A - Palindromic Supersequence
433A - Kitahara Haruki's Gift
672A - Summer Camp
1277A - Happy Birthday Polycarp
577A - Multiplication Table
817C - Really Big Numbers
1355A - Sequence with Digits
977B - Two-gram
993A - Two Squares
1659D - Reverse Sort Sum
1659A - Red Versus Blue
1659B - Bit Flipping
1480B - The Great Hero
1519B - The Cake Is a Lie
1659C - Line Empire
515A - Drazil and Date
1084B - Kvass and the Fair Nut
1101A - Minimum Integer
985D - Sand Fortress
1279A - New Year Garland
1279B - Verse For Santa