hdoj-1548简单的bfs题目

//运用队列和搜索结合,一切更简单

#include <bits/stdc++.h>
#define maxn 2006

using namespace std;
const int INF=3000;
int op[]= {-1,1};
int N;
int s,g;
int d[maxn];
int mase[maxn];
int dfs()
{
    queue<int>que;
    for(int i=1; i<=N; i++) d[i]=INF;
    d[s]=0;
    que.push(s);
    while(que.size())
    {
        int p=que.front();
        que.pop();
        if(p==g) break;
        for(int i=0; i<=1; i++)
        {
            int nx=p+op[i]*mase[p];
            if(nx>=1&&nx<=N&&d[nx]==INF)
            {
                que.push(nx);
                d[nx]=d[p]+1;
            }
        }
    }
    return d[g];
}
int main()
{
    while(scanf("%d",&N)&&N)
    {
        memset(d,0,sizeof(0));
        scanf("%d %d",&s,&g);
        for(int i=1; i<=N; i++) scanf("%d",&mase[i]);
        int result =dfs();
        if(result>200) printf("-1 ");
        else printf("%d ",result);
    }
    return 0;
}

原文地址:https://www.cnblogs.com/cshg/p/5276445.html