省份数量

题目:
有 n 个城市,其中一些彼此相连,另一些没有相连。如果城市 a 与城市 b 直接相连,且城市 b 与城市 c 直接相连,那么城市 a 与城市 c 间接相连。

省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。

给你一个 n x n 的矩阵 isConnected ,其中 isConnected[i][j] = 1 表示第 i 个城市和第 j 个城市直接相连,而 isConnected[i][j] = 0 表示二者不直接相连。

返回矩阵中 省份 的数量。

示例 1:

输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]]
输出:2
示例 2:

输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]]
输出:3

解题思路:本题可以用dfs或者bfs来进行解答,遍历数组,当遇到没有到达过的城市时,找到该城市可以达到并且之前没有达到过的城市即可

DFS:

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        
        boolean book[] = new boolean[n];
        int ans = 0;
        for(int i = 0; i < n; i++) {
            if(!book[i]) {
                dfs(i, isConnected, book);
                ans++;
            }
        }
        
        return ans;
    }
    
    private void dfs(int cur, int[][] isConnected, boolean[] book) {
        
        book[cur] = true;
        
        for(int i = 0; i < isConnected.length; i++) {
            if(!book[i] && isConnected[cur][i] == 1) {
                dfs(i, isConnected, book);
            }
        }
        
    }
}

BFS

class Solution {
    public int findCircleNum(int[][] isConnected) {
        int n = isConnected.length;
        
        boolean book[] = new boolean[n];
        
        Queue<Integer> queue = new LinkedList();
        
        int ans = 0;
        
        for(int i = 0; i < n; i++) {
            if(!book[i]) {
                queue.offer(i);
                book[i] = true;
                while(!queue.isEmpty()) {
                    int cur = queue.poll();
                    for(int j = 0; j < n; j++) {
                        if(!book[j] && isConnected[cur][j] == 1) {
                            queue.offer(j);
                            book[j] = true;
                        }
                    }
                }
                
                ans++;
            }
        }
        
        return ans;
    }
}
posted on 2021-01-07 10:25  KobeSacre  阅读(71)  评论(0编辑  收藏  举报