haechandev
Algorithms

[Baekjoon 1520] Downhill

A memoized DFS that counts paths by walking backward from the destination to higher neighbors.

January 12, 2023

We could count downhill paths from the start directly. My implementation instead starts at the destination and walks backward to higher cells. The number of downhill paths arriving at a cell becomes the sum of the path counts of its higher neighbors.

ways(y, x) = Σ ways(higher adjacent cell)

I used -1 for an uncomputed state and nonnegative values for computed path counts. Heights strictly decrease along a forward path, so there are no cycles. That makes DFS with memoization a good fit.

Problem: Baekjoon · Code: View on GitHub