Depth_first algorithm