-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkContagion.java
More file actions
81 lines (56 loc) · 2.09 KB
/
Copy pathNetworkContagion.java
File metadata and controls
81 lines (56 loc) · 2.09 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
import java.util.Scanner;
class TreeNode {
String name;
TreeNode left;
TreeNode right;
TreeNode(String name) {
this.name = name;
}
}
public class NetworkContagion {
private int maxTime;
public int minutesToInfect(TreeNode root, String start) {
maxTime = 0;
dfs(root, start);
return maxTime;
}
private int dfs(TreeNode node, String start) {
if (node == null)
return 0;
int left = dfs(node.left, start);
int right = dfs(node.right, start);
if (node.name.equalsIgnoreCase(start)) {
maxTime = Math.max(
maxTime, Math.max(left, right));
return -1;
}
if (left < 0 || right < 0) {
int infectedDistance = Math.min(left, right);
maxTime = Math.max(
maxTime,
Math.abs(infectedDistance) + Math.max(left, right)
);
return infectedDistance - 1;
}
return 1 + Math.max(left, right);
}
public static void main(String[] args) {
TreeNode A = new TreeNode("A");
TreeNode B = new TreeNode("B");
TreeNode C = new TreeNode("C");
TreeNode D = new TreeNode("D");
TreeNode E = new TreeNode("E");
A.left = B;
A.right = C;
B.left = D;
C.right = E;
Scanner scanner = new Scanner(System.in);
System.out.println("Network Nodes: A, B, C, D, E");
System.out.print("Enter starting node: ");
String startNode = scanner.nextLine();
NetworkContagion simulation = new NetworkContagion();
int minutes = simulation.minutesToInfect(A, startNode);
System.out.println("Minutes to infect network: " + minutes);
scanner.close();
}
}