Skip to content

Commit 3d2af97

Browse files
William FisetWilliam Fiset
William Fiset
authored and
William Fiset
committed
longest path tweak
1 parent 369900f commit 3d2af97

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

src/main/java/com/williamfiset/algorithms/graphtheory/treealgorithms/TreeCenterLongestPathImpl.java

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,24 @@
1212

1313
public class TreeCenterLongestPathImpl {
1414

15-
private static int[] dfs(
15+
private static class DfsResult {
16+
// The distance to the furthest node (from where the DFS started)
17+
int distance;
18+
19+
// The index of the furthest node (from where the DFS started)
20+
int index;
21+
22+
public DfsResult(int distance, int index) {
23+
this.distance = distance;
24+
this.index = index;
25+
}
26+
}
27+
28+
private static DfsResult dfs(
1629
List<List<Integer>> graph, boolean[] visited, int[] prev, int at, int parent) {
1730

1831
// Already visited this node
19-
if (visited[at]) return new int[] {0, parent};
32+
if (visited[at]) return new DfsResult(0, parent);
2033

2134
// Visit this node
2235
visited[at] = true;
@@ -28,15 +41,15 @@ private static int[] dfs(
2841
List<Integer> edges = graph.get(at);
2942

3043
for (int to : edges) {
31-
int[] tuple = dfs(graph, visited, prev, to, at);
32-
int dist = tuple[0] + 1;
44+
DfsResult result = dfs(graph, visited, prev, to, at);
45+
int dist = result.distance + 1;
3346
if (dist > bestDist) {
3447
bestDist = dist;
35-
index = tuple[1];
48+
index = result.index;
3649
}
3750
}
3851

39-
return new int[] {bestDist, index};
52+
return new DfsResult(bestDist, index);
4053
}
4154

4255
public static List<Integer> findTreeCenters(List<List<Integer>> graph) {
@@ -48,7 +61,8 @@ public static List<Integer> findTreeCenters(List<List<Integer>> graph) {
4861
int[] prev = new int[n];
4962

5063
// Do DFS to find furthest node from the start
51-
int furthestNode1 = dfs(graph, visited, prev, 0, -1)[1];
64+
DfsResult result = dfs(graph, visited, prev, 0, -1);
65+
int furthestNode1 = result.index;
5266

5367
// Singleton
5468
if (furthestNode1 == -1) {
@@ -59,7 +73,9 @@ public static List<Integer> findTreeCenters(List<List<Integer>> graph) {
5973
// Do another DFS, but this time from the furthest node.
6074
Arrays.fill(visited, false);
6175
Arrays.fill(prev, 0);
62-
int furthestNode2 = dfs(graph, visited, prev, furthestNode1, -1)[1];
76+
77+
result = dfs(graph, visited, prev, furthestNode1, -1);
78+
int furthestNode2 = result.index;
6379

6480
List<Integer> path = new LinkedList<>();
6581
for (int i = furthestNode2; i != -1; i = prev[i]) {

0 commit comments

Comments
 (0)