bfs题:社交网络
问题:
思路:
需注意的点:
- 邻接表的表示方法为List< Integer >[] arrayList,即一个数组,数组元素为List< Integer >
- 在队列中存放的节点除了节点编号外,还需保存节点入队的时间,用于退出循环。节点出队时,获取该节点入队的时间,若节点入队的时间>= t,则退出循环,因为入队时间为t的结点出队时,接下来进行的是第t + 1小时的感染
- 为判断集合中的结点是否全被感染,还需用count记录被感染的节点数目,看是否等于S的大小。在退出循环后进行判断count是否等于k
代码:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.Iterator;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Main {
static List<Integer>[] arrayList;
static Set<Integer> set = new HashSet<>();
static int count = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] ans = new int[1005];
int n = scanner.nextInt();
arrayList = new List[n + 1];
int m = scanner.nextInt();
int i;
for (i = 0;i <= n;i++) {
arrayList[i] = new ArrayList<>();
}
for (i = 0;i < m;i++) {
int head = scanner.nextInt();
int tail = scanner.nextInt();
arrayList[head].add(tail);
arrayList[tail].add(head);
}
int k = scanner.nextInt();
long t = scanner.nextLong();
for (i = 0;i < k;i++) {
set.add(scanner.nextInt());
}
int[] visit = new int[n + 1];
Iterator<Integer> iterator = set.iterator();
int flag = 0;
i = 0;
while (iterator.hasNext()) {
for (int ll = 0;ll < visit.length;ll++) {
visit[ll] = 0;
}
int host = iterator.next();
if (bfs(host, t, visit, k)) {
ans[i] = host;
i++;
flag = 1;
}
}
if (flag == 0) {
System.out.print(-1);
} else {
int j;
Arrays.sort(ans,0,i);
for (j = 0;j < i;j++) {
System.out.print(ans[j] + " ");
}
}
}
public static boolean bfs(int host, long depth, int[] visit, int k) {
LinkedList<DataAndTime> linkedList = new LinkedList<>();
DataAndTime dataAndTime = new DataAndTime(host, 0);
linkedList.add(dataAndTime);
visit[host] = 1;
count = 1;
long time;
while (!linkedList.isEmpty()) {
DataAndTime element = linkedList.pop();
time = element.time;
if (time >= depth) {
break;
}
List<Integer> array = arrayList[element.host];
for (int p = 0; p < array.size(); p++) {
if (!set.contains(array.get(p))) {
return false;
}
if (visit[array.get(p)] == 0) {
linkedList.add(new DataAndTime(array.get(p), time + 1));
visit[array.get(p)] = 1;
count++;
}
}
}
if (count == k) {
return true;
}
return false;
}
static class DataAndTime {
int host;
long time;
public DataAndTime(int host, long time) {
this.host = host;
this.time = time;
}
}
}