0

I understand there are 3 common ways to represent graphs:

  1. Adjacency Matrix
  2. Adjacency List
  3. Edge list

That said, problems I’ve solved on LeetCode often use matrices and the solution requires DFS or BFS. For example, given the matrix below, find if a target string exists when you go left, right, up, and down (but not diagonal).

[
  [‘a’,‘p’,’p’],
  [‘e’,’a’,’l’],
  [‘r’,’t’,’e’]
]

This required a DFS approach. Is this because this matrix represents a graph or does DFS and BFS apply to matrices too and not just trees and graphs?

Are DFS and BFS always/mostly used against matrices (2D arrays) in implementation or are there cases where it’s used against a Graph class?

jth_92
  • 1,120
  • 9
  • 23

1 Answers1

2

Graph algorithms are often used to solve problems on data structures that do not explicitly represent a graph, like your matrix. The graph is not in the data. It's in your head when you solve the problem. For example, "If I think of this as a graph, the I can solve the problem with DFS or BFS". Then you write a BFS or DFS algorithm, mapping the traversal operations to whatever is equivalent in the data structure you do have.

This is called operating on the "implicit graph": https://en.wikipedia.org/wiki/Implicit_graph

If you actually made a graph data structure out of your data -- an explicit graph -- then you could write a BFS or DFS on that directly, but it's often unnecessary and in fact wasteful.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • Thanks. I was getting confused at understanding the implementation of graph algorithms when many practice problems didn't actually use explicit graphs. It also helps connect this to heaps which has a 1d array as the data structure implementation. As a follow-up question, what are common indications that I should use BFS/DFS as opposed to typical array traversal? Everywhere I've read describes when to use one vs the other but not necessarily how to identify that BFS/DFS should be used in the first place. – jth_92 Apr 26 '20 at 22:43
  • Nothing simple, I'm afraid. You have to know a lot of graph algorithms so that you can tell when one of them applies to the problem you have to solve, even if the problem doesn't look like a graph. You can find implicit graphs in just about everything -- the trick is knowing which ones are useful and when. – Matt Timmermans Apr 26 '20 at 23:03