Light propagation in optical waveguides: a dynamic programming approach