题目链接
// 3.广度优先,11ms,5.92%
public int findCircleNum(int[][] arr) {
int citys = arr.length;
boolean[] visited = new boolean[citys];
int provinces = 0; // 计数器
Queue<Integer> queue = new LinkedList<>();
for(int i = 0; i < citys; i++) {
if(!visited[i]) {
queue.offer(i);
while(!queue.isEmpty()) {
int k = queue.poll();
visited[k] = true;
for(int j = 0; j < citys; j++) { // 广度遍历
if(arr[k][j] == 1 && !visited[j]) { // 没有被访问的话就进行添加到后一次的遍历
queue.offer(j);
}
}
}
provinces++;
System.out.println(i);
}
}
return provinces;
}