g = ExampleData[{"NetworkGraph", "ZacharyKarateClub"}]
dm = GraphDistanceMatrix[g];
Position[dm, Max[dm]]
(* {{15, 20}, {15, 24}, {15, 25}, {15, 29}, {15, 30}, {15,
31}, {15, 32}, {15, 33}, {20, 15}, {24, 15}, {25, 15}, {29,
15}, {30, 15}, {31, 15}, {32, 15}, {33, 15}} *)
pair = VertexList[g][[#]] & /@ First[%]
(* {17, 24} *)
path = FindShortestPath[g, Sequence @@ pair]
(* {17, 6, 1, 3, 28, 24} *)
HighlightGraph[g, {Style[pair, Yellow],
Style[UndirectedEdge @@@ Partition[path, 2, 1], Red]}]
The IGraph/M package has a fast function for this that avoids keeping the entire distance matrix in memory. I recommend it for large graphs.
<< IGraphM`
IGraph/M 0.3.91 (May 5, 2017)
Evaluate IGDocumentation[] to get started.
?IGFindDiameter
IGFindDiameter[graph]
returns a longest shortest path in graph, i.e. a shortest path with length equal to the graph diameter. Available Method
options: {"Unweighted", "Dijkstra"}
.
HighlightGraph[g, PathGraph@IGFindDiameter[g]]