-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.py
More file actions
23 lines (22 loc) · 856 Bytes
/
DFS.py
File metadata and controls
23 lines (22 loc) · 856 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class DFS:
def __init__(self, graph):
self.graph = graph
self.stack = []
self.visited = set()
def DFSFromNode(self, nodeID):
#mark that nodeID has been visited
self.visited.add(nodeID)
# get neighbor of nodeID
neighbors_of_nodeID=self.graph[nodeID].getNeighbors()
#make sure neighbors don't contain the node we have visited
effective_neighbors=neighbors_of_nodeID-self.visited
#add effective neighbors into the begining of the stack
for i in effective_neighbors:
self.stack.insert(0,i)
while len(self.stack)>0:
#get the node start next
start_next=self.stack[0]
#delete this node from stack
del self.stack[0]
#search from node 'start_next'
self.DFSFromNode(start_next)