**
法一
**
import java.util.*;
public class Main {
public static void main(String[] args) {
//处理输入
Scanner sc = new Scanner(System.in);
String reporter = sc.nextLine();//发布者
int m = Integer.parseInt(sc.nextLine());//几组数,组数
//动态数组里加数组
List<String[]> list = new ArrayList<>();
//将数据导入到动态数组中
for (int i = 0; i < m; i++) {
list.add(sc.nextLine().split(","));
}
//bfs
//新建一个队列
Queue<String> queue = new LinkedList<>();
//新建一个指示这个数组是否被访问
int[] maked = new int[m];
//队列中加入初始发布者
queue.add(reporter);
//循环
while (!queue.isEmpty()) {
//出队(FIFO)
String someReporter = queue.poll();
//循环判断所有链表里的数据
for (int j = 0; j < list.size(); j++) {
//获取当前索引下的数组里的人名
String[] s = list.get(j);
//遍历当前数组里的人名,并且要求当前数组没有被访问过,访问过--跳出
for (int i = 0; i < s.length && maked[j] != 1; i++) {
//当前数组包含要搜索的人名,及他能访问当前数组,将当前数组的元素压入队列
if (s[i].equals(someReporter)) {
//数组转化为列表
List<String> stringList = Arrays.asList(s);
//添加入队列
queue.addAll(stringList);
//将当前标记数组置为1,表示已经访问过了
maked[j] = 1;
}
}
}
}
//获取所有接收信息人群的集合
Set<String> set = new HashSet<>();
//遍历动态数组
for (int i = 0; i < m; i++) {
//标记数组为1,代表着个数组里的人都能收到消息
if (maked[i] == 1) {
//将人名放入set降重, 数组--列表
set.addAll(Arrays.asList(list.get(i)));
}
}
int setSize = set.size();
System.out.println(setSize);
}
}
**
法二:
**
先把第一个含有最先带消息的群组所有人加到set,然后在遍历剩下的群组,如果群组内有人在set里就把整个群组加到set里,去重操作set自动就做好了。最后直接输出set的size就行了。
import java.util.*;
public class Main {
public static void main(String[] args) {
//处理输入
Scanner sc = new Scanner(System.in);
String reporter = sc.nextLine();//发布者
int m = Integer.parseInt(sc.nextLine());//几组数,组数
//动态数组里加数组
List<String[]> list = new ArrayList<>();
//将数据导入到动态数组中
for (int i = 0; i < m; i++) {
list.add(sc.nextLine().split(","));
}
//获取所有接收信息人群的集合
Set<String> set = new HashSet<>();
set.add(reporter);
//遍历动态数组
for (int i = 0; i < m; i++) {
for(int j = 0; j < list.get(i).length; j++){
if(set.contains(list.get(i)[j])){
set.addAll(Arrays.asList(list.get(i)));
}
}
}
int setSize = set.size();
System.out.println(setSize);
}
}