MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / dfs

Method dfs

graphs/directed_and_undirected_weighted_graph.py:302–338  ·  view source on GitHub ↗
(self, s=-2, d=-1)

Source from the content-addressed store, hash-verified

300
301 # if no destination is meant the default value is -1
302 def dfs(self, s=-2, d=-1):
303 if s == d:
304 return []
305 stack = []
306 visited = []
307 if s == -2:
308 s = next(iter(self.graph))
309 stack.append(s)
310 visited.append(s)
311 ss = s
312
313 while True:
314 # check if there is any non isolated nodes
315 if len(self.graph[s]) != 0:
316 ss = s
317 for node in self.graph[s]:
318 if visited.count(node[1]) < 1:
319 if node[1] == d:
320 visited.append(d)
321 return visited
322 else:
323 stack.append(node[1])
324 visited.append(node[1])
325 ss = node[1]
326 break
327
328 # check if all the children are visited
329 if s == ss:
330 stack.pop()
331 if len(stack) != 0:
332 s = stack[len(stack) - 1]
333 else:
334 s = ss
335
336 # check if se have reached the starting point
337 if len(stack) == 0:
338 return visited
339
340 # c is the count of nodes you want and if you leave it or pass -1 to the function
341 # the count will be random from 10 to 10000

Callers 1

dfs_timeMethod · 0.95

Calls 3

countMethod · 0.80
appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected