Skip to content
DeepForgeby svx
All problems
MediumGraph Algorithmsgraph-031

Graph Diameter by BFS

Problem

Compute the diameter of a connected undirected unweighted graph: the maximum shortest-path distance between any two nodes.

Run a BFS from every node and take the largest distance found. Return -1 when the graph is disconnected and 0 for a single node.

Hint

The longest BFS distance over all starting nodes is the diameter.

Test cases

case 1
in: [5,[[0,1],[1,2],[2,3],[3,4]]]
expected: 4
case 2
in: [4,[[0,1],[0,2],[0,3]]]
expected: 2
case 3
in: [4,[[0,1],[2,3]]]
expected: -1
case 4
in: [1,[]]
expected: 0
case 5
in: [2,[[0,1]]]
expected: 1
Starter codePython
def graph_diameter(n, edges):
    # Your code here
    pass

5 test cases · run your code against them in the editor