Skip to content

Instantly share code, notes, and snippets.

@markormesher
Created August 25, 2018 15:21
Show Gist options
  • Save markormesher/f883c61450e75c8c414c8aeafcc1469c to your computer and use it in GitHub Desktop.
Save markormesher/f883c61450e75c8c414c8aeafcc1469c to your computer and use it in GitHub Desktop.
# input: startingNode
openList = [] # nodes we have discovered but haven't visited yet
closedList = [] # nodes we have already visited, store so we don't go back to them
# if the open list is a stack, we have DFS
# if the open list is a queue, we have BFS
# if the open list is a min/max-heap that uses some function of node properties, we have heuristic search
# the closed list can be a simple set; order is not important
# the starting node is all we've "discovered" so far
openList.add(startingNode)
# as long as there's something left to explore...
while (openList is not empty) {
# pick one node to visit
node = remove one item from openList
# do something with this node (problem-specific)
visit(node)
# add it to the closed list to indicate "we've been there"
closedList.add(node)
# add all of the node's children to the open list, as long as we haven't already visisted them
for (child in node.children) {
if (closedList does not containc child) {
openList.add(child)
}
}
}
# when we break out of the loop we will have visited every node that is reachable from the starting node
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment