Finding a route from one city to another
Four classes:
Node
name
Edge
source
and dest
which are substances of class Node
Digraph
edges
is a K-V
sets data, K
for source node, and V
for destination node.addNode
to add Node object as the K
of edges
.addEdge
to add Edge object, which will append the dest
property of Edge object to edges
with the specific K
.chirdrenOf
to return all the child nodeshasNode
in self.edges
getNode
by node’s nameGraph - is a subclass of Digraph
addEdge
: rewrite the addEdge
method to add another set with reversed source and destination nodes.Similar to left-first depth-first method of enumerating a search tree, mainly difference is that graph might have cycles, so we must keep track of what nodes we have visited
Implement Codes
1 | def DFS(graph, start, end, path, shortest, toPrint): |
Explore the nodes layer by layer, like first we got a node as start node, then check all the children nodes, then children’s children, it will keep going until we got the node equal the end node. And that’s the path we are looking for, just return it.
Implement Codes
1 | """ Explore all paths with n hops |
digraph ['daiɡrɑ:f, -ɡræf] n. 有向图