google-deepmind / clrs

Apache License 2.0
452 stars 87 forks source link

What does DFS output result mean ? #113

Closed hwchen1 closed 1 year ago

hwchen1 commented 1 year ago
from clrs._src.algorithms import graphs
import networkx as nx

DIRECTED = np.array(
    [
        [0, 1, 0, 1, 0, 0],
        [0, 0, 0, 0, 1, 0],
        [0, 0, 0, 0, 1, 1],
        [0, 1, 0, 0, 0, 0],
        [0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 1],
    ]
)
out, _ = graphs.dfs(DIRECTED)
print(out)  # [0 0 2 4 1 2]

What does the result of executing the code output mean? If there are multiple results in DFS, how to judge whether it is right or wrong?

PetarV- commented 1 year ago

Hi, thanks for your issue!

The results (the array [0 0 2 4 1 2] in this case), completely specify the DFS tree.

Specifically, the DFS algorithm traverses the graph in a specific way, and whenever it explores a new node from a neighbour, that neighbour becomes the "parent" of the node in the DFS tree. The array you referenced contains all the parents.

So the tree (more specifically, forest in this case) looks something like:

2 <- 5
0 <- 1 <- 4 <- 3

And the predecessors are represented in the array you see. Note that, by convention, we make the roots (0 and 2) predecessors of themselves.

Your second question (on judging right vs. wrong) can be interpreted in two ways; let me try to answer both of them:

I hope this is helpful! Please let me know if there are any other questions you might have.

Thanks, Petar