BFS的应用一(相邻转换)

题目描述:

矩阵中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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值