Implement the Depth-First Search Algorithm - Implement the Depth-First Search Algorithm

Tell us what’s happening:

I pass all the test except 7. I don’t understand why

  1. The dfs function should return the correct results.

Your code so far

visited = []

def dfs(adja_matrix: list, node_label: int):
    
    if node_label not in visited:
        visited.append(node_label)
    
        for i, v in enumerate(adja_matrix[node_label]):
            if v == 1:
                if i not in visited:
                  dfs(adja_matrix, i)
                
    return visited


Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:149.0) Gecko/20100101 Firefox/149.0

Challenge Information:

Implement the Depth-First Search Algorithm - Implement the Depth-First Search Algorithm

Adding couple function calls below might give some hints what’s happening. Ie.:

print(dfs([[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]], 3))
print(dfs([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], 3))

Thanks!!! I have tried one at a time :person_facepalming: It was the global variable doing spells.

Two nested functions and one nonlocal variable have passed all the tests.

Thank you very much!