More memory-efficient code for determining routes