Pr 入門教程,如何使用色輪?
阿新 • • 發佈:2021-11-30
有 n 個城市,其中一些彼此相連,另一些沒有相連。如果城市 a 與城市 b 直接相連,且城市 b 與城市 c 直接相連,那麼城市 a 與城市 c 間接相連。
省份 是一組直接或間接相連的城市,組內不含其他沒有相連的城市。
給你一個 n x n 的矩陣 isConnected ,其中 isConnected[i][j] = 1 表示第 i 個城市和第 j 個城市直接相連,而 isConnected[i][j] = 0 表示二者不直接相連。
返回矩陣中 省份 的數量。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/number-of-provinces
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
並查集
class Solution { public int findCircleNum(int[][] isConnected) { if (isConnected == null || isConnected.length == 0 || isConnected[0].length == 0) { return 0; } int n = isConnected.length; UnionSet unionSet = new UnionSet(n); unionSet.init(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (isConnected[i][j] == 1) { unionSet.union(i + 1, j + 1); } } } return unionSet.count(); } } class UnionSet { private int n; private int[] parent; private int[] size; public UnionSet(int n) { this.n = n; this.parent = new int[n + 1]; this.size = new int[n + 1]; } public void init() { for (int i = 1; i <= n; ++i) { parent[i] = i; size[i] = 1; } } public int find(int x) { int f = parent[x]; while (parent[f] != f) { f = parent[f]; } while (x != f) { int t = parent[x]; parent[x] = f; x = t; } return f; } public void union(int a, int b) { int fa = find(a); int fb = find(b); if (fa == fb) { return; } if (size[fa] > size[fb]) { parent[fb] = fa; size[fa] += size[fb]; size[fb] = 0; } else { parent[fa] = fb; size[fb] += size[fa]; size[fa] = 0; } } public int count() { int ret = 0; for (int i = 1; i <= n; ++i) { if (parent[i] == i) { ret++; } } return ret; } }
搜尋
心之所向,素履以往 生如逆旅,一葦以航class Solution { public int findCircleNum(int[][] isConnected) { int provinces = isConnected.length; boolean[] visited = new boolean[provinces]; int circles = 0; Queue<Integer> queue = new LinkedList<Integer>(); for (int i = 0; i < provinces; i++) { if (!visited[i]) { queue.offer(i); while (!queue.isEmpty()) { int j = queue.poll(); visited[j] = true; for (int k = 0; k < provinces; k++) { if (isConnected[j][k] == 1 && !visited[k]) { queue.offer(k); } } } circles++; } } return circles; } }