Graphs Graph basics
431. BFS and DFS of a Graph
You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in
edges is an edge between vertices u and v, and it can be used in both directions.
Return two lists: the order in which a breadth-first search (BFS) visits the vertices, and the order in
which a depth-first search (DFS) visits them. Both searches start at vertex 0. Whenever a search looks
at the neighbours of a vertex, it looks at them in increasing order of their numbers, whatever order edges
lists them in. This rule makes each order unique.
- The BFS order starts with vertex
0. Then it takes the vertices already in the order one by one, from the first. For each one it adds that vertex's neighbours that are not in the order yet, smallest first. - The DFS order starts with vertex
0too. From the current vertex it moves to the smallest neighbour that is not in the order yet, adds it, and goes on from there. When the current vertex has no such neighbour left, it steps back to the vertex it came from and goes on there.
A vertex that cannot be reached from vertex 0 is in neither list. Return the BFS order first and the DFS
order second, as [bfs, dfs].
Example 1
Input: n = 6
edges = [[0, 3],
[4, 2],
[0, 1],
[1, 4],
[2, 5],
[3, 4]]
[[0,1,3,4,2,5],[0,1,4,2,5,3]]Explanation: BFS visits 0, then its neighbours 1 and 3, then 4, two edges away, then 2 and 5. DFS goes as deep as it can, 0 → 1 → 4 → 2 → 5, then steps back to 4 and visits 3.
Example 2
Input: n = 5, edges = [[3, 4], [2, 0], [1, 0]]
[[0,1,2],[0,1,2]]Explanation: Vertex 0 has the neighbours 2 and 1, and both searches visit 1 first because it is smaller. Vertices 3 and 4 are joined to each other but not to vertex 0, so neither search reaches them.
Example 3
Input: n = 1, edges = []
[[0],[0]]Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 2 × 105edges[i].length == 20 ≤ ui, vi < nui ≠ vi- No edge appears twice:
[u, v]and[v, u]are the same edge.
Clarifying questions
What you would ask an interviewer before writing any code.