【LeetCode练习】[中等]547. 省份数量

【LeetCode练习】[中等]547. 省份数量

547. 省份数量

547. 省份数量

算法思想:数组

题目:

【LeetCode练习】[中等]547. 省份数量_第1张图片
相当于求这个图中的连通分量有多少,可以用DFS,BFS,并查集
如下记录DFS BFS

java代码-DFS

class Solution {
     public int findCircleNum(int[][] isConnected) {
        int num = isConnected.length;
        int count = 0;
        boolean[] visit = new boolean[num];//用来标记节点是否访问过
        for (int i = 0; i < num; i++) {
            if (!visit[i]) {
                visit[i] = true;//标记当前节点访问过
                myDfs(isConnected, visit, num, i);//DFS向下查找一次,则连通分量加一
                count++;//连通分量加一
            }
        }
        return count;
    }

    private void myDfs(int[][] isConnected, boolean[] visit, int num, int node) {
        for (int i = 0; i < num; i++) {//查找相邻节点,是否能到达
            if (!visit[i] && isConnected[node][i] == 1) {//如果相邻能连通
                visit[i] = true;//标记当前节点访问过
                myDfs(isConnected, visit,num, i);//用相邻节点,向下递归
            }
        }
    }
}

java代码-BFS

class Solution {
     public int findCircleNum(int[][] isConnected) {
        int num = isConnected.length;
        int count = 0;
        boolean[] visit = new boolean[num];
        Queue<Integer> queue = new LinkedList<>();
        //开始遍历
        for (int i =0 ; i < num; i++){
            if(!visit[i]){
                queue.offer(i);
                visit[i] = true;
                while (!queue.isEmpty()) {
                    int node = queue.poll();
                    for (int j =0 ; j < num; j++){
                        if(!visit[j] && isConnected[node][j] == 1){
                            queue.offer(j);
                            visit[j] = true;
                        }
                    }
                }
                count++;
            }
        }
        return count;
    }
}

java代码-并查集

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int provinces = isConnected.length;
        int[] parent = new int[provinces];
        for (int i = 0; i < provinces; i++) {
            parent[i] = i;
        }
        for (int i = 0; i < provinces; i++) {
            for (int j = i + 1; j < provinces; j++) {
                if (isConnected[i][j] == 1) {
                    union(parent, i, j);
                }
            }
        }
        int circles = 0;
        for (int i = 0; i < provinces; i++) {
            if (parent[i] == i) {
                circles++;
            }
        }
        return circles;
    }

    public void union(int[] parent, int index1, int index2) {
        parent[find(parent, index1)] = find(parent, index2);
    }

    public int find(int[] parent, int index) {
        if (parent[index] != index) {
            parent[index] = find(parent, parent[index]);
        }
        return parent[index];
    }
}

你可能感兴趣的:(LeetCode,leetcode,java,算法)