In a maze represented by an array, does a path exist between point A (row RA, column CA) point B (row RB, column CB) ? bool path(RA, CA, RB, CB) { if (wall[RA][CA]) return false; if (RA==RB && CA==CB) return true; if (path(RA-1, CA, RB, CB)) return true; if (path(RA+1, CA, RB, CB)) return true; if (path(RA, CA-1, RB, CB)) return true; if (path(RA, CA+1, RB, CB)) return true; return false; } int path_length(RA, CA, RB, CB) // 999999 means impossible { if (wall[RA][CA]) return 999999; if (RA==RB && CA==CB) return 0; int solution1 = path_length(RA-1, CA, RB, CB), solution2 = path_length(RA+1, CA, RB, CB), solution3 = path_length(RA, CA-1, RB, CB), solution4 = path_length(RA, CA+1, RB, CB); int best = min(solution1, solution2, solution3, solution4); if (best == 999999) return 999999; return 1 + best; } That is a depth-first-search (DFS). In this example, it repeats the same computations very many times, and it is likely to find long paths before short ones. We could solve the first problem by making it remember what it has already tried. The second problem is part of the nature of DFS.