BFS

http://poj.org/problem?id=3278


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iomanip>

using namespace std;
#define maxn 100005
#define MOD 1000000007
#define mem(a , b) memset(a , b , sizeof(a))
#define LL long long
#define ULL unsigned long long

bool used[maxn];

typedef struct
{
    int x,step;
}Point;

bool overwall(int x)
{
    if(x<0||x>=maxn)
        return true;
    else
        return false;
}

void bfs(int n,int k)
{
    Point t,p;
    t.step=0;
    t.x=n;
    used[t.x]=true;
    queue <Point> q;
    q.push(t);
    int b[3][2]={{1,0},{-1,0},{0,1}};
    while (!q.empty()) {
        p=q.front();
        q.pop();
        if(p.x==k)
        {
            cout<<p.step<<endl;
            break;
        }
        for(int i=0;i<3;i++)
        {
            t=p;
            t.x=t.x+b[i][0]+t.x*b[i][1];
            if(!overwall(t.x)&&!used[t.x])
            {
                t.step++;
                q.push(t);
                used[t.x]=true;
            }
        }
    }
}

int main()
{
    int  N,K;
    while (cin>>N>>K) {
        memset(used,0,sizeof(used));
        bfs(N,K);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiao-xue-di/p/9441658.html