版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mike_learns_to_rock/article/details/88628935
题目
题目描述:一张含n节点的无向图,以及一组无向边,编写一个函数来查找无向图中连接的组件的数量。
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]
0 3
| |
1 --- 2 4
Output: 2
分析
解法DFS/BFS/并查集,DFS和BFS时间复杂度均为O(e + n), 并查集时间复杂度O(e + n)(路径压缩的权重quickUnion算法union接近O(1));e是edges的长度,n是节点数量;
解法
DFS
public class Solution {
// 搜索区域
private Map<Integer, List<Integer>> relation = new HashMap<>();
// 已搜索的标志,当然也可以用Set
private boolean[] hasSearch;
public int countComponents(int n, int[][] edges) {
if (n < 1) {
return 0;
}
hasSearch = new boolean[n];
for (int i = 0; i < n; i++) {
relation.put(i, new LinkedList<>());
}
// 关键:构建一个搜索区域,不像《岛屿的数量》题目直接构建好了搜索区域int[][] grid;
for (int i = 0; i < edges.length; i++) {
relation.get(edges[i][0]).add(edges[i][1]);
relation.get(edges[i][1]).add(edges[i][0]);
}
int count = 0;
// 连通图问题的计算数量的模版
for (int i = 0; i < n; i++) {
if (!hasSearch[i]) {
dfs(i);
count++;
}
}
return count;
}
private void dfs(int i) {
for (Integer son : relation.get(i)) {
if (!hasSearch[son]) {
hasSearch[son] = true;
dfs(son);
}
}
}
}
BFS
public class Solution {
private Map<Integer, List<Integer>> relation = new HashMap<>();
private boolean[] hasSearch;
public int countComponents(int n, int[][] edges) {
if (n < 1) {
return 0;
}
hasSearch = new boolean[n];
for (int i = 0; i < n; i++) {
relation.put(i, new LinkedList<>());
}
for (int i = 0; i < edges.length; i++) {
relation.get(edges[i][0]).add(edges[i][1]);
relation.get(edges[i][1]).add(edges[i][0]);
}
int count = 0;
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (!hasSearch[i]) {
count++;
queue.clear();
queue.add(i);
while (!queue.isEmpty()) {
int cur = queue.poll();
if (!hasSearch[cur]) {
hasSearch[cur] = true;
for (Integer e : relation.get(cur)) {
if (!hasSearch[e]) {
queue.offer(e);
}
}
}
}
}
}
return count;
}