广度优先搜索练习之神奇的电梯
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
有一座已知层数为n的高楼,这座高楼的特殊之处在于只能靠电梯去上下楼,所以要去到某一层要非常耽误时间,然而更悲哀的是,这座高楼的电梯是限号的,小鑫最开始的时候在1层,他想去第x层,问题是他最起码要经过多少层(包含第x层)才能到达第x层。
Input
多组输入。
第一行是三个正整数n,m,q。分别代表楼的总层数,给定的m条信息和q次查询。
接下来的m行,每行的第一个整数pos代表这是第pos层的电梯,第二个数代表从这一层可以去的楼层总共有num个,之后的num个数字代表从第pos层代表可以去的楼层。
最后的q行,每行一个整数代表小鑫想去的楼层号码。
1<=m,pos,num<=n<=200
1<=q<=20
Output
对于每次询问输出一个整数,占一行。代表如果要去某个楼层最少要经过多少层,如果到不了的话就输出-1。
Sample Input
10 4 3 1 2 6 7 3 4 4 6 8 10 5 2 2 3 7 3 10 5 6 4 5 9
Sample Output
5 3 -1
Hint
Source
Casithy
bfs。。
从目标楼层开始搜索,直到搜索到第一层或者遍历结束。
#include <bits/stdc++.h>
using namespace std;
struct node{
int b, a;
}p, t, r;
bool Map[210][210], v[210];
void bfs(int n, int x);
int main(){
int n, m, q, pos, a, x;
while(cin >> n >> m >> q){
memset(Map, false, sizeof(Map));
while(m--){
cin >> pos >> a;
for(int i = 1; i <= a; i++){
cin >> x;
Map[pos][x] = true;
}
}
while(q--){
cin >> x;
bfs(n, x);
}
}
return 0;
}
void bfs(int n, int x){
queue <node> q;
memset(v, false, sizeof(v));
p.b = x;
p.a = 1;
q.push(p);
while(!q.empty()){
t = q.front();
q.pop();
if(t.b == 1){
cout << t.a << endl;
return;
}
for(int i = 1; i <= n; i++){
if(Map[i][t.b] && !v[i]){
v[i] = true;
r.b = i;
r.a = t.a + 1;
q.push(r);
}
}
}
cout << "-1" <<endl;
}