C - Catch That Cow[bfs]

博客围绕C语言中“Catch That Cow”问题展开,涉及一条线上的搜索,行动有三种走的方式,分别为+1、 -1、 *2。

C - Catch That Cow

一条线上的搜索
行动有三种情况,就计做三种走的方式 +1, -1, *2

struct node{
        int pos,step;
};

struct node head;
queue <struct node> q;
int N,K;//起始位置和终止位置
int vis[len];
int main(){
	while (cin >> N >> K) {
            
          Init();
          bfs();
      }
    return 0;
}
void Init(){
    memset(vis, 0, sizeof(vis));
        
    while (!q.empty()) q.pop();
        
    struct node tmp;
    vis[N] = 1;
    tmp.pos = N; tmp.step = 0;
    q.push(tmp);
}
void bfs(){
    while (!q.empty()) {
        head = q.front();
        q.pop();
        if(head.pos == K){cout << "0" << endl; continue;}
        //有可能不用跑 。这里有个坑
            
        for (int i=0; i<3; i++) {
            switch (i) {
                case 0:{
                   int _x = head.pos + 1;
                   if (_x == K) {cout << head.step + 1 << endl;return;}
                   if (_x >= len) continue;
                   if (vis[_x] == 1) continue;
                   struct node tmp;
                   tmp.pos = _x; tmp.step = head.step + 1;
                   q.push(tmp);
                   vis[_x] ++;
                   break;
               }
               case 1:{
                   int _x = head.pos - 1;
                   if (_x == K) {cout << head.step + 1 << endl;return;}
                   if (_x < 0) continue;
                   if (vis[_x] == 1) continue;
                   struct node tmp;
                   tmp.pos = _x; tmp.step = head.step + 1;
                   q.push(tmp);
                   vis[_x] ++;
                   break;
               }
               case 2:{
                   int _x = head.pos * 2;
                   if (_x == K) {cout << head.step + 1 << endl;return;}
                   if (_x >= len) continue;
                   if (vis[_x] == 1) continue;
                   struct node tmp;
                   tmp.pos = _x; tmp.step = head.step + 1;
                   q.push(tmp);
                   vis[_x] ++;
                   break;
               }
            }
       }
   }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值