Rewritten code to use NetworkX for graph manipulations.