B - Rectangle Detection Editorial by en_translator
General notes
When treating strings in a programming language, in many languages the first character is the \(0\)-th character, so be sure to check the language you use to implement.
Solution 1. Try all \(A, B, C\), and \(D\)
First, we introduce a naive solution. An efficient solution is explained in Solution 2.
There are only \(3025(=55 \times 55)\) tuples of integers \((A,B,C,D)\) such that
- \(1 \le A \le B \le 10\);
- \(1 \le C \le D \le 10\).
By actually generating from \(S_1\) through \(S_{10}\) and comparing with the input, you can get AC (accepted) for this problem with about \(302500\) operations (multiplied by a constant factor).
Sample code (C++):
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<string> s(10);
for(int i=0;i<10;i++){cin >> s[i];}
for(int a=1;a<=10;a++){
for(int b=a;b<=10;b++){
for(int c=1;c<=10;c++){
for(int d=c;d<=10;d++){
vector<string> t(10);
for(int i=1;i<=10;i++){
for(int j=1;j<=10;j++){
if(a<=i && i<=b && c<=j && j<=d){
t[i-1].push_back('#');
}
else{
t[i-1].push_back('.');
}
}
}
if(s==t){
cout << a << " " << b << "\n" << c << " " << d << "\n";
}
}
}
}
}
return 0;
}
Solution 2. An efficient solution
The generated string contains exactly one rectangle consisting of #
s. Thus, one can determine \(A, B, C\), and \(D\) as follows:
- \(A=\) (The topmost row containing
#
); - \(B=\) (The bottommost row containing
#
); - \(C=\) (The leftmost column containing
#
); - \(D=\) (The rightmost column containing
#
).
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<string> s(10);
for(int i=0;i<10;i++){cin >> s[i];}
int a=1e9,b=-1e9;
int c=1e9,d=-1e9;
for(int i=0;i<10;i++){
for(int j=0;j<10;j++){
if(s[i][j]=='#'){
a=min(a,i+1);
b=max(b,i+1);
c=min(c,j+1);
d=max(d,j+1);
}
}
}
cout << a << " " << b << "\n";
cout << c << " " << d << "\n";
return 0;
}
posted:
last update: