2
votes

A robot located at the top left corner of a XxX grid is trying to reach the bottom right corner. The robot can move either up, down, left, or right, but cannot visit the same spot twice. How many possible unique paths are there to the bottom right corner?

What is a fast algorithmic solution to this? I've spent a huge amount of time trying to figure out a fast algorithm to this. But still stuck.

This is basically the unique paths Leetcode problem, except with backtracking.

Unique paths, without backtracking, can be solved with dynamic programming such as:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<int> cur(n, 1);
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                cur[j] += cur[j - 1];
            }
        }
        return cur[n - 1];
    }
};

What would be a fast algorithmic solution, using dynamic programming, to unique paths, except with backtracking? Something that could quickly find the result 1,568,758,030,464,750,013,214,100 for a 10X10 grid.

Reddit, Wikipedia, and Youtube have resources illustrating the complexity of this problem. But they don't have any answers.

1
Why does it need to be with backtracking? I suspect a part of description is missing, since backtracking is about enumerating and not counting the solutions. It's also a bit strange to use backtracking, since you're not really pruning solution space (besides not visiting same spot twice, I guess). - domen
backtracking as I know is about using recursive function, you can write recursive backtrack algorithm and use memoization - oybek
leetcode.com/problems/unique-paths is not the same. The only operations allowed in that problem is right and down whereas you're allowing up, down, left and right. Do you have link to the original problem statement? - Mukul Gupta
math.stackexchange.com/questions/23111/… Here's a combinatorics solution - Photon

1 Answers

2
votes

The problem cannot be solved using dynamic programming because the recurrence relation does not break the problem into sub-problems. Dynamic programming assumes that the state to be computed is dependent on only the sub-states in the recurrence. It is not true in this case because there can be cycles, ie. going up and down.

The general case of this problem, to count the number of simple paths in a directed cyclic graph, is considered to be #P-Complete.

This can also been as enumerating self avoiding walks in 2-dimensions. As per wikipedia,

Finding the number of such paths is conjectured to be an NP-hard problem[citation needed].

However, if we consider moves in only the positive direction, ie. right and down, it has a closed form solution, of m+nCm. Basically, the total number of moves is always fixed to be m + n where m,n are cartesian distances to the end point of the diagonal and we simply have to choose the m right(s) or n down(s). The dynamic programming solution is essentially the same.