Modified the algorithm for path