-1

I understand the concept of depth first search when it comes to traversing trees. But I am having a hard time how to perform dfs on other data structures (arrays, 2d arrays, etc). What is the best way to think about this?

2 Answers2

1

The DFS will create a virtual tree on every structure you apply it to. This tree is known as a spanning tree of the structure. They exist for graphs, digraphs and even arrays or other structures than can be visited by a DFS.

spanning tree of a grid graph

Of course there will be many edges that won't be on that tree. In undirected graphs and structures, they're always "back edges" (that go from a child node to an ancestor node), but on strucutres where the edges may have a specific orientation, they can be forward edges (that point to unvisited descendant nodes) or cross edges (that cross different subtrees).

spanning tree

Juan Lopes
  • 10,143
  • 2
  • 25
  • 44
0

Depth First Search (DFS) is typically demonstrated on trees. Now, how you implement the trees is your call. You can implement using Arrays, Linked Lists, Adjacency Matrix, etc. The best way to understand is to implement one, here are few implementations that can help:

  1. DFS on an array
  2. DFS and BFS using Linked List
Community
  • 1
  • 1
PseudoAj
  • 5,234
  • 2
  • 17
  • 37