finalizing path algorithm