| 34 | |
| 35 | # if no destination is meant the default value is -1 |
| 36 | def dfs(self, s=-2, d=-1): |
| 37 | if s == d: |
| 38 | return [] |
| 39 | stack = [] |
| 40 | visited = [] |
| 41 | if s == -2: |
| 42 | s = next(iter(self.graph)) |
| 43 | stack.append(s) |
| 44 | visited.append(s) |
| 45 | ss = s |
| 46 | |
| 47 | while True: |
| 48 | # check if there is any non isolated nodes |
| 49 | if len(self.graph[s]) != 0: |
| 50 | ss = s |
| 51 | for node in self.graph[s]: |
| 52 | if visited.count(node[1]) < 1: |
| 53 | if node[1] == d: |
| 54 | visited.append(d) |
| 55 | return visited |
| 56 | else: |
| 57 | stack.append(node[1]) |
| 58 | visited.append(node[1]) |
| 59 | ss = node[1] |
| 60 | break |
| 61 | |
| 62 | # check if all the children are visited |
| 63 | if s == ss: |
| 64 | stack.pop() |
| 65 | if len(stack) != 0: |
| 66 | s = stack[len(stack) - 1] |
| 67 | else: |
| 68 | s = ss |
| 69 | |
| 70 | # check if se have reached the starting point |
| 71 | if len(stack) == 0: |
| 72 | return visited |
| 73 | |
| 74 | # c is the count of nodes you want and if you leave it or pass -1 to the function |
| 75 | # the count will be random from 10 to 10000 |