笔试题目-无向图是否全连通

笔试中遇到的题:

  给你 N 个小岛,求这 N 个小岛是否是连通的,比如:小岛 1 与  2 连通,1 与 3 连通,则 1、2、3 这三个小岛都是连通的。

  给定一个无向图的邻接矩阵,其中 0 表示不可达,1表示可以到达。

思路:

  利用无向图的邻接矩阵,通过递归遍历即可,统计已经连通的小岛个数 islandConnectedCount,当个数为 N 时,则表示 N 个小岛都连通了,返回 true ;否则,当遍历完整个矩阵后,还是 islandConnectedCount  !=  N ,表示 N 个小岛没有全部连通,返回 false.

public class Solution {
    private static int islandConnectedCount = 0; //设为全局变量,方便每一轮递归都可以访问到
    public static void main(String[] args) {
        int[][] map = new int[][]{
                {0,1,0,0,0,1},
                {1,0,1,1,0,0},
                {0,1,0,0,1,0},
                {0,1,0,0,1,0},
                {0,0,1,1,0,0},
                {1,0,0,0,0,0}
        }; //无向图的邻接矩阵
        boolean[] flag = new boolean[map.length];
        flag[0] = true; //初始第 0 座小岛可达
        islandConnectedCount = 1;
        System.out.println(isConnected(map, flag,0)); //从编号为 0 的小岛开始遍历
    }
    public static boolean isConnected(int[][] map, boolean[] flag,int curNumber){
        //map为邻接矩阵;flag为标记此小岛是否已连通;curNumber为当前的小岛编号
        if(islandConnectedCount == map.length) return true; //已经连通的小岛个数
        for(int i = 0; i < map.length; i++){
            if(map[curNumber][i] == 0 || flag[i] == true){
                continue; // 当前小岛与第 i 个小岛没有路,或者已经遍历过了,则跳过
            }else {
                flag[i] = true; // 设置第 i 座小岛为可到达
                islandConnectedCount++;
                boolean res = isConnected(map,flag,i);
                if(res == true) return true;
            }
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/luo-c/p/13683844.html