跳至主要内容

329. 矩阵中的最长递增路径

class Solution {
public:
   
    int longestIncreasingPath(vector<vector<int>> &matrix)
    {
        if (matrix.size() == 0)
            return 0;
       
        int xmax = matrix.size();
        int ymax = matrix[0].size();

        int ** tmp = new int*[xmax];

        for (int i = 0; i < xmax; i++)
        {
            tmp[i] = new int[ymax];
            for (int j = 0; j < ymax; j++)
            {
                tmp[i][j] = 0;
            }
        }

        int maxlen = 0;
        for (int i = 0; i < xmax; i++)
        {
            for (int j = 0; j < ymax; j++)
            {
                maxlen = max(maxlen, dp(matrix, i, j, tmp, xmax, ymax));
            }
        }

        return maxlen;
    }

    int dp(vector<vector<int>> &matrix, int i, int j, int ** tmp, int xmax, int ymax)
    {
        if (tmp[i][j] != 0)
        {
            return tmp[i][j];
        }

        int xdir[4] = { 1, 0, -1, 0 };
        int ydir[4] = { 0, 1, 0, -1 };

        tmp[i][j] = 1;

        for (int k = 0; k < 4; k++)
        {
            int x = i + xdir[k];
            int y = j + ydir[k];

            if (x >= 0 && x < xmax && y >= 0 && y < ymax && matrix[x][y]>matrix[i][j])
            {
                int maxlen = max(dp(matrix, x, y, tmp, xmax, ymax) + 1, tmp[i][j]);
                tmp[i][j] = maxlen;
            }
        }

        return tmp[i][j];
    }
};

评论

此博客中的热门博文

ubuntu 添加root登录

Login to your server as root. As the root user, edit the sshd_config file found in  /etc/ssh/sshd_config : vim /etc/ssh/sshd_config ( For details on working with Vim check out our article here !) Add the following line to the file, you can add it anywhere but it’s good practice to find the block about authentication and add it there. PermitRootLogin yes Save and exit the file. Restart the SSH server: systemctl restart sshd or service sshd restart