Updated to handle already visited nodes