题目链接
    image.png

    1. // 3.广度优先,11ms,5.92%
    2. public int findCircleNum(int[][] arr) {
    3. int citys = arr.length;
    4. boolean[] visited = new boolean[citys];
    5. int provinces = 0; // 计数器
    6. Queue<Integer> queue = new LinkedList<>();
    7. for(int i = 0; i < citys; i++) {
    8. if(!visited[i]) {
    9. queue.offer(i);
    10. while(!queue.isEmpty()) {
    11. int k = queue.poll();
    12. visited[k] = true;
    13. for(int j = 0; j < citys; j++) { // 广度遍历
    14. if(arr[k][j] == 1 && !visited[j]) { // 没有被访问的话就进行添加到后一次的遍历
    15. queue.offer(j);
    16. }
    17. }
    18. }
    19. provinces++;
    20. System.out.println(i);
    21. }
    22. }
    23. return provinces;
    24. }