- Mark all nodes as not visited.
- Create an empty
readybucket to hold nodes that has been visited itself but not its neighbors yet. - Find a starting
node, mark it as visited and put into thereadybucket. - Get an
nodefrom thereadybucket and look at its directly connected neighbors. Skip those that are visited already, mark the rest asvisitedand put them into thereadybucket. - Repeat 4 until
readyis empty.
Depends on how you operate ready bucket, you can achieve BFS (breadth first search) or DFS (depth first search).
- BFS: use
readyas a queue, operations are queue and dequeue, aka FIFO - DFS: use
readyas a stack, operations are push and pop, aka FILO
Path finding#
If you also need to trace the path, what you can do is:
- Setup a
dictforpathwhose key and value are both nodes, while key is current node, value is previous node. - Setup a
dictforcostwhose key is node and value is the minimum cost to get to that node. - For each step of the traverse,
- Instead of looking at
visited, you need to calculate each node’s cost. If next node’s cost is lower than recorded, replace the code and put next node intoreadyeven though they are visited already. - You need to update the
pathwith current step’s next nodes, if they are not visited, or visited but with higher cost.
- Instead of looking at
- When destination node is reached, but
readyis still not empty, you need to continue, because future path could have lower cost. - When a path is found to a particular destination node, you can use this
pathdictionary to walk back the history step by step.