| Problem statement | Source code | Tags: BFS/DFS
The problem forms a tree because of the following observations:
COM that does not orbit anything (unique root)."Direct orbits" are parent-child relationships; "indirect orbits" are ancestor-descendant relationships. Thus, for each node in the tree, we just count the number of ancestors. This is the depth of the node. Depths can be computed with either BFS or DFS; I prefer BFS.
We want to find the shortest path from YOU to SAN. Since this is a tree, there is a unique path between any two nodes. Again this is a BFS, starting at YOU, searching for SAN. The result is depth - 2, since we want to exclude the starting and ending nodes.