oneby7

Graphs Graph basics

431. BFS and DFS of a Graph

Easy

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 0 too. 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

012345

Input: n = 6 edges = [[0, 3], [4, 2], [0, 1], [1, 4], [2, 5], [3, 4]]

Output: [[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

01234

Input: n = 5, edges = [[3, 4], [2, 0], [1, 0]]

Output: [[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

0

Input: n = 1, edges = []

Output: [[0],[0]]

Check your understanding

Work out the answer for this input before you write any code.

n = 5 edges = [[0, 1], [0, 3], [1, 2], [2, 3], [2, 4]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 2 × 105
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • ui ≠ 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.