题目描述:
矩阵中1代表项目经理,2代表程序员,0代表空,问至少几步能将所有项目经理都转换为程序员,如果能完全转换返回步数,不能完全转换返回-1。如果2与1相邻则可以将1一步转换为2。例如
1 2 0 2 2 0 2 2 0 2 2 0
2 1 1 -> 2 2 1 -> 2 2 2 ->2 2 2
1 0 1 2 0 1 2 0 1 2 0 2
因此step=3;
输入样例:
1 2 0
2 1 1
1 0 1
输出
3
参考代码:
#include <iostream>
#include<utility>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int num[12][12];
int state[12][12];
int offset[4][2]={1,0,0,1,-1,0,0,-1};
int main()
{
int i,j,step=0;
char ch;
memset(num,0,sizeof(num));
memset(state,0,sizeof(state));
cin.get(ch);
for(i=0;i<12;++i)
{
for(j=0;j<12;)
{
if(ch!=' '&&ch!='\n') {num[i][j]=ch-'0';++j;}
if(ch=='\n') break;
cin.get(ch);
}
cin.get(ch);
if(ch=='\n') break;
}
bool flag=false;
int cnt2=0,cnt2_temp=0;
queue<pair<int,int> >q;
for(int t=0;t<=i;++t)
for(int s=0;s<j;++s)
{
if(num[t][s]==2) {
q.push(pair<int,int>(t,s));
++cnt2;
state[t][s]=1;
}
}
while(!q.empty())
{
pair<int,int>f=q.front();
q.pop();
--cnt2;
for(int k=0;k<4;++k)
{
int x=f.first+offset[k][0];
int y=f.second+offset[k][1];
if(x<=i&&y<j&&state[x][y]==0&&num[x][y]==1)
{
flag=true;
num[x][y]=2;
state[x][y]=1;
q.push(pair<int,int>(x,y));
++cnt2_temp;
}
}
if(cnt2<=0){
if(!flag) break;
if(flag)
{
cnt2=cnt2_temp;
cnt2_temp=0;
++step;
flag=false;
}
}
}
bool ishas=true;
for(int t=0;t<=i;++t)
{
for(int s=0;s<j;++s)
if(num[t][s]==1) ishas=false;
}
if(ishas)
{
if(step<=0) cout<<-1<<endl;
else cout<<step<<endl;
}
else cout<<-1<<endl;
return 0;
}