-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindCircleNum.java
More file actions
104 lines (94 loc) · 2.54 KB
/
Copy pathFindCircleNum.java
File metadata and controls
104 lines (94 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
* File Name:FindCircleNum is created on 2020/9/27 10:37 下午 by lite
*
* Copyright (c) 2020, xiaoyujiaoyu technology All Rights Reserved.
*
*/
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author lite
* @Description: 1. dfs
* 2. bfs
* 3. unionFind
* @date: 2020/9/27 10:37 下午
* @since JDK 1.8
*/
public class FindCircleNum {
public void findCircleNum(int[][] M) {
System.out.println(dfs(M));
System.out.println(bfs(M));
}
public int dfs(int[][] M) {
int[] visited = new int[M.length];
int count = 0;
for (int i = 0; i < M.length; i++) {
if (visited[i] == 0) {
recur(M, visited, i);
count++;
}
}
return count;
}
public void recur(int[][] M, int[] visited, int i) {
for (int j = 0; j < M.length; j++) {
if (M[i][j] == 1 && visited[j] == 0) {
visited[j] = 1;
recur(M, visited, j);
}
}
}
public int bfs(int[][] M) {
int[] visited = new int[M.length];
int count = 0;
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < M.length; i++) {
if (visited[i] == 0) {
queue.add(i);
while (!queue.isEmpty()) {
int s = queue.remove();
visited[s] = 1;
for (int j = 0; j < M.length; j++) {
if (M[s][j] == 1 && visited[j] == 0) {
queue.add(j);
}
}
}
count++;
}
}
return count;
}
public int unionFind(int[][] M) {
int[] parent = new int[M.length];
Arrays.fill(parent, -1);
for (int i = 0; i < M.length; i++) {
for (int j = 0; j < M.length; j++) {
if (M[i][j] == 1 && i != j) {
union(parent, i, j);
}
}
}
int count = 0;
for (int i = 0; i < parent.length; i++) {
if (parent[i] == -1) {
count++;
}
}
return count;
}
int find(int[] parent, int i) {
if (parent[i] == -1) {
return i;
}
return find(parent, parent[i]);
}
void union(int[] parent, int x, int y) {
int fx = find(parent, x);
int fy = find(parent, y);
if (fx != fy) {
parent[fx] = fy;
}
}
}