Longest Increasing Path in a Matrix二维矩阵中最长递增路径

思路:
设,当前点x(i,j)为终点的最长递增路径长度为f(x(i,j));
则,当前点的上下左右节点为终点的最长递增路径长度分别为f(x(i-1,j)), f(x(I+1,j)), f(x(i,j-1)), f(x(i,j+1));
此时,如果当前节点的值大于上下左右节点的值,则以当前节点为终点,上一步沿上下左右节点走向当前节点的递增路径长度依次为:
up=f(x(i-1,j))+1,
down=f(x(I+1,j))+1,
left= f(x(i,j-1))+1,
right= f(x(i,j+1))+1;
如果当前节点的值不大于上下左右节点的值,则up,down,left,right的值为1。
最终,f(x(i,j)) = max(up, down, left, right)。

举例:

1		2		3	
4		5		6
其中,
1为终点的最长递增路径为:1,长度为1;
2为终点的最长递增路径为:1-2,长度为2;
3为终点的最长递增路径为:1-2-3,长度为3;
4为终点的最长递增路径为:1-4,长度为2;
5为终点的最长递增路径为:1-4-5,长度为3;
6为终点的最长递增路径为:1-4-5-6,长度为4;

代码:

int LongIncPath(vector>& a, vector>& dp, int i, int j){
    int col = (int)a[0].size();
    int row = (int)a.size();
    if (dp[i][j] != 0) {
        return dp[i][j];
    }
    // 左右上下
    int l=1, r=1, u=1, d=1;
    if (j>0 && a[i][j]>a[i][j-1]) {
        l = 1+LongIncPath(a, dp, i, j-1);
    }
    if (ja[i][j+1]) {
        r = 1+LongIncPath(a, dp, i, j+1);
    }
    if (i>0 && a[i][j]>a[i-1][j]) {
        u = 1+LongIncPath(a, dp, i-1, j);
    }
    if (ia[i+1][j]) {
        d = 1+LongIncPath(a, dp, i+1, j);
    }
    dp[i][j] = max(max(l,r),max(u,d));
    return dp[i][j];
}

int main() {
    vector> a(2);
    for (int i= 0; i < a.size(); i++) {
        a[i].resize(3);
    }
    for (int i=0; i < a.size(); i++) {
        for (int j=0; j < a[0].size(); j++) {
            a[i][j] = i*(int)a[0].size() + j + 1;
        }
    }
    vector d(a[0].size(), 0);
    vector> dp(a.size(), d);
    
    int col = (int)a[0].size();
    int row = (int)a.size();
    
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            if (dp[i][j] != 0) {
                continue;
            }
            else {
                dp[i][j] = LongIncPath(a, dp, i, j);
            }
            cout << i << " " << j << " is " << a[i][j] << ", deep path is " << dp[i][j] << endl;
        }
    }
}
输出结果:
0 0 is 1, deep path is 1
0 1 is 2, deep path is 2
0 2 is 3, deep path is 3
1 0 is 4, deep path is 2
1 1 is 5, deep path is 3
1 2 is 6, deep path is 4

你可能感兴趣的:(C++,面试刷题)