Below is an assignment for algorithm class where we are learning about nodes, paths, etc. The code is designed to check if one node is reachable from another. The code below works but I am unclear why. G is the "graph" containing each node as a key with values = the nodes it connects to. The mark_component function below returns a number of nodes from a given node.
However in the function check_connection which is designed to return True if two nodes are reachable, it calls this mark_component function and then tests to see if a node is in a dictionary.
What I do not get is check_connection starts with an empty dictionary "marked" and then calls mark_component using this dictionary. Nodes are then added to it. But mark_component returns a number so how does the check_connection function able to "read" what is in marked? As far as that function is concerned, I thought marked would still be empty. I guess I assumed marked was a local variable containing a dictionary but it apparently can be passed to another function and changed.
Can anyone please explain this to me? Many thanks
def mark_component(G, node, marked):
marked[node] = True
total_marked = 1
for neighbor in G[node]:
if neighbor not in marked:
total_marked += mark_component(G, neighbor, marked)
return total_marked
def check_connection(G, v1, v2):
# Return True if v1 is connected to v2 in G
# or False if otherwise
marked = {}
mark_component(G, v1, marked)
return 'a' in marked
G = {'a': {'d': 1, 'g': 1}, 'c': {'g': 1}, 'b': {'f': 1},
'e': {'h': 1, 'f': 1}, 'd': {'a': 1, 'g': 1},
'g': {'a': 1, 'c': 1, 'd': 1}, 'f': {'b': 1, 'e': 1}, 'h': {'e': 1}}
print check_connection(G,'a', 'b')