Is two blocks because the first block is at node #0.
Node #1 has no incoming reference. Node #2 and Node #3 have references are are adjacent so it's just one block.
The Idea: Iterate through the references. If the either the left or right node has been visited, that means our current reference will belong to an already existing connected component. If this is not true, then we've introduced a new connected component.
Complexity: O(n) time and space.
defdll_n_connected(refs): visited =set() blocks =0# references assumed to be uniquefor ref in refs: visited.add(ref)if(not ref.left andnot ref.right in visited) blocks +=1elif(not ref.right andnot ref.left in visited) blocks +=1elifnot(ref.left in visited or ref.right in visited) blocks +=1return blocks