Code: Select all
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
int t;
cin>>t;
int tc=0;
while(t--)
{
tc++;
int r,c;
cin>>r>>c;
map<int ,string>m;
for(int i=0;i<r;i++)
{
string temp;
string temp2="2";
cin>>temp;
temp2+=temp;
temp2+="2";
m[i]=temp2;
}
int javab=1<<30;
for(int j=1;j<c+1;j++)
{
if(javab==-1)
break;
bool ra=false,ch=false;
int col=0;
for(int i=0;i<r;i++)
{
bool rast=true,chap=true;
int k,kk;
if(m[i][j]=='1')
{
for(k=j+1;k<m[i].size();k++)
{
if(m[i][k]=='0')
break;
if(m[i][k]=='2')
rast=false;
}
for(kk=j-1;kk>=0;kk--)
{
if(m[i][kk]=='0')
break;
if(m[i][kk]=='2')
chap=false;
}
if(chap==true && rast==false)
col+=kk;
if(chap==false && rast==true)
col+=k;
if(chap==true && rast==true)
{
if(k<kk)
col+=k;
else
col+=kk;
}
if(chap==false && rast==false)
{
javab=-1;
break;
}
}
}
if(col<javab)
javab=col;
}
cout<<"Case "<<tc<<": "<<javab;
if(t!=0)
cout<<endl;
}
}
![:)](./images/smilies/icon_smile.gif)