kuangbin专题一 catch the cow (BFS)

BFS例题

注意:1. 超过100000时跳出 2. 如果到右边再回来,一定没有直接从左边过去划算

代码:

// zyc 2018/8/20

#include 
#include 
#include 
#include 
using namespace std;

typedef long long ll;
const int maxn = 100000 + 7;
const int inf = 0x3f3f3f3f;

int m, k;
int dis [maxn];
bool cheak (int l)
{
    if (l >= 0 && l <= 100000 && dis[l] == inf) return true;
    else return false;
}
void bfs ()
{
    memset (dis, inf, sizeof (dis));
    int s1, s2;
    queue  res;
    dis[m] = 0;
    res.push(m);
    while (!res.empty()) {
        s1 = res.front ();
        if (s1 == k) {printf ("%d\n", dis[s1]); return ;}
        res.pop();
        s2 = s1;
        if (cheak (s2 + 1)) { dis[s2 + 1] = dis[s2] + 1; res.push(s2 + 1);}
        s2 = s1;
        if (cheak (s2 * 2)) { dis[s2 * 2] = dis[s2] + 1; res.push(s2 * 2);}
        s2 = s1;
        if (cheak (s2 - 1)) { dis[s2 - 1] = dis[s2] + 1; res.push(s2 - 1);}
    }
}
int main ()
{
    while (~scanf ("%d %d", &m, &k)) {
        bfs ();
    }
    return 0;
}

 

你可能感兴趣的:(DFS&&BFS,kuangbin,1)