Completed depth first search function