fixed the code to handle both directed and undirected graph