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

Tell us what’s happening:

So far after just trying to crack the code, I accidentally came up with a partial solution, I just don’t know what the second parameter is for. And I’m hoping that I’m visualizing the matrix and task correctly (below is the mental image of how I see it’s supposed to be processed for example test case 2 which was correct) I just don’t know what the other parameter is for.

Your code so far

# testcase 2
"""
  A  B  C  D
A[0, 1, 0, 0]
B[1, 0, 1, 0]
C[0, 1, 0, 1]
D[0, 0, 1, 0]
"""

def dfs(matrix, n):
    depth = []
    deep = 0

    combined_increment = 0
    node_increment = 0
    for value in matrix:
        
        for node in value:
            
            if node == 1:
                #This handles the first list
                if combined_increment != 0:
                    #This makes sure we don't count pathways already travelled by checking the previous list at an index that is one higher than the index of where "1" was found in the current list
                    if matrix[combined_increment -1 ][node_increment +1]:
                        deep += 1
                        depth.append(deep)
                        
        combined_increment += 1

    # this handles the last case when there are no more pathways
    depth.append(0)
  
    return depth


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0

Challenge Information:

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

waaaaaiiiiit, I just realized that n is the node you start from!!!

and also I thought the function returned a list of the lengths of each pathway, but it just returns the nodes visited! huge face palm moment, yes I know i’m talking to a wall, just had to say it

1 Like

Hi @justinnyakundi232 ,

Would it help to use this Python Code Visualizer to step through your code?

Happy coding!

1 Like