forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
85 lines (73 loc) · 2.2 KB
/
Solution.java
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
/**
* @author Oleg Cherednik
* @since 31.04.2019
*/
public class Solution {
public static void main(String... args) {
System.out.println(isMinimallyConnected(createMinimumConnected1())); // false;
System.out.println(isMinimallyConnected(createNotMinimumConnected1())); // false;
System.out.println(isMinimallyConnected(createNotMinimumConnected2())); // false;
}
private static int[][] createMinimumConnected1() {
return new int[][] {
{ 6, 2, 1, 5 },
{ 0 },
{ 0 },
{ 5, 4 },
{ 3 },
{ 3, 0 },
{ 0 } };
}
private static int[][] createNotMinimumConnected1() {
return new int[][] {
{ 6, 2, 1, 5 },
{ 0 },
{ 0 },
{ 5, 4 },
{ 3 },
{ 3, 0 },
{ 0 },
{ 8 },
{ 7 },
{ 11, 10, 12 },
{ 9 },
{ 9 },
{ 9 } };
}
private static int[][] createNotMinimumConnected2() {
return new int[][] {
{ 6, 2, 1, 5 },
{ 0 },
{ 0 },
{ 5, 4 },
{ 5, 6, 3 },
{ 3, 4, 0 },
{ 0, 4 },
{ 8 },
{ 7 },
{ 11, 10, 12 },
{ 9 },
{ 9, 12 },
{ 11, 9 } };
}
public static boolean isMinimallyConnected(int[][] adjacencyList) {
boolean[] marked = new boolean[adjacencyList.length];
if (!dfs(0, 0, adjacencyList, marked))
return false;
for (int i = 0; i < marked.length; i++)
if (!marked[i])
return false;
return true;
}
private static boolean dfs(int v, int u, int[][] adjacencyList, boolean[] marked) {
marked[v] = true;
for (int w : adjacencyList[v]) {
if (marked[w]) {
if (w != u)
return false;
} else if (!dfs(w, v, adjacencyList, marked))
return false;
}
return true;
}
}