题目大意:
一个电梯,给出起始位置和终止位置,每次只能上升或者下降特定的层数,问能不能到达指定位置
解题思路:
用bfs来做,电梯路线可以形成一个二叉树,每一步相当于一层,两种选择形成两个分支,每搜索一次相当于走一步
代码:
# include <iostream> # include <cstring> # include <queue> using namespace std; int f[300]; bool visit[300]; struct Node { int dir, move; }; int bfs(int a, int b,int N) { Node t,t1; t.dir = a; t.move = 0; visit[t.dir] = 1; queue<Node>q; q.push(t); while (!q.empty()) { t = q.front(); q.pop(); if (t.dir == b) return t.move; if (t.dir - f[t.dir] >= 1&&!visit[t.dir - f[t.dir]]) { t1.move = t.move + 1; t1.dir= t.dir - f[t.dir]; visit[t1.dir] = 1; q.push(t1); } if (t.dir + f[t.dir] <= N && !visit[t.dir + f[t.dir]]) { t1.move = t.move + 1; t1.dir = t.dir + f[t.dir]; visit[t1.dir] = 1; q.push(t1); } } return -1; } int main() { int N, A, B; while (cin >> N&&N != 0) { memset(visit, 0, sizeof(visit)); cin >> A >> B; for (int i = 1; i <=N; ++i) cin >> f[i]; cout << bfs(A, B, N) << endl; } return 0; }