Now handles cycles in graphs correctly