HDOJ1548(BFS)

来源:互联网 发布:安全狗防sql注入原理 编辑:程序博客网 时间:2024/05/19 17:51

大意:n层楼,坐电梯从a层到b层。第i层有一个数Ki,可以上到i+Ki层,可以下到i-K层。求最少几次能从a到b层。

分析:BFS水题。

代码

#include<iostream>#include<cstdio>#include<queue>#include<cstring>using namespace std;int n, a, b;int k[205];int e[205];queue<int>q;int bfs(int x, int y){memset(e, 0, sizeof(e));while (!q.empty())q.pop();int sum = 0;q.push(x);e[x] = 1;while (!q.empty()) {if (q.front() == y)return e[y]-1;int m = k[q.front()] + q.front();if (m > 0 && m <= n&&!e[m]){q.push(m);e[m] = e[q.front()]+1;}int t = q.front() - k[q.front()];if (t > 0 && t <= n&&!e[t]){q.push(t);e[t] = e[q.front()] + 1;}q.pop();}return -1;}int main(){while (scanf("%d", &n) != EOF&&n){scanf("%d%d", &a, &b);for (int i = 1; i <= n; i++)scanf("%d", &k[i]);printf("%d\n", bfs(a, b));}return 0;}


0 0
原创粉丝点击