Classic algorithm without backtrace.