I am practicing my coding on leetcode, and my submission, although correct for small cases, is timing out for large ones. Could you please let me know how to improve my code?
The question is as follows (https://leetcode.com/problems/longest-increasing-path-in-a-matrix/):
Given an integer matrix, find the length of the longest increasing path. From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Here is my solution. I tried to use memoization, but it's just not fast enough: I think I'm missing something fundamental -- I do not have a CS background.
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix)
{
//base case
if (matrix.size() == 0 || matrix[0].size() == 0)
return 0;
//create hash matrix populated with -1
int height = matrix.size();
int length = matrix[0].size();
vector<int> temp(length,-1);
vector<vector<int>> hash(height,temp);
int maximum;
//run longestpathfrom on all node
for(int i=0; i<height; i++)
{
for(int j = 0; j<length; j++)
{
longestpathfrom(matrix,i,j,hash,maximum);
}
}
return maximum;
}
int longestpathfrom(vector<vector<int>> matrix, int i, int j, vector<vector<int>>& hash, int& maximum)
{
//Returns the longest path from your current position
//Also uses memoization via hash.
//also keeps track of the max...
//If you already calculated this value, just return it.
if (hash[i][j]!=-1)
return hash[i][j];
//directions
vector<vector<int>> dirs {{-1,0},{1,0},{0,-1},{0,1}};
//pathlength:
int pathlen = 0;
//Take the max of longestpathfrom over all valid neighbours:
for (int I=0; I<4; I++)
{
//Generate indices of where you are checking path length from
int x = i+dirs[I][0];
int y = j+dirs[I][1];
//Check index validity:
if (x<0 || y<0 || x>matrix.size()-1 || y>matrix[0].size()-1)
continue;
if (matrix[i][j]<matrix[x][y])
pathlen = max(pathlen, longestpathfrom(matrix, x, y, hash, maximum));
}
//add 1 for the square you're already on
pathlen++;
//update hash
hash[i][j]=pathlen;
//update max
maximum = max(maximum,pathlen);
return pathlen;
}
};
vector
s by reference may be alleviated being const correct (Eckel/Meyers)const vector<const vector<int>> matrix
. \$\endgroup\$