class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { int m=matrix.size(); if(m == 0) return 0; int n=matrix[0].size(); if(n == 0 ) return 0; vector<int> row(n,0); vector<vector<int>> len(m,row); //cout<<m<<endl; //cout<<n<<endl; int max_len = 0; for(int i=0;i<m;i++) for(int j=0;j<n;j++) { //cout<<i<<" "<<j<<endl; max_len=max(max_len,getlen(matrix,len,i,j)); } return max_len; } int getlen(vector<vector<int>>& matrix,vector<vector<int>>& len,int i,int j){ int m=matrix.size(); int n=matrix[0].size(); //cout<<"i="<<i<<" j="<<j<<endl; if(i<0 || i> m-1 || j<0 || j>n-1) {return 0;} if(len[i][j] != 0) {cout<<len[i][j]<<endl; return len[i][j];} int a,b,c,d; a=b=c=d=1; if(i==0) a=1; else { if(matrix[i][j]<matrix[i-1][j]) a=getlen(matrix,len,i-1,j)+1; } // cout<<"a="<<a<<endl; if(i==m-1) b=1; else { if(matrix[i][j]<matrix[i+1][j]) b=getlen(matrix,len,i+1,j)+1; } // cout<<"b="<<b<<endl; if(j==0) c=1; else { if(matrix[i][j]<matrix[i][j-1]) c=getlen(matrix,len,i,j-1)+1; } // cout<<"c="<<c<<endl; if(j==n-1) d=1; else { if(matrix[i][j]<matrix[i][j+1]) d=getlen(matrix,len,i,j+1)+1; } // cout<<"d="<<d<<endl; len[i][j] = max(a,max(b,max(c,d))); return len[i][j]; } };
a.b.c.d分别表示上下左右;
备忘录的思想;
数字的大小关系决定了不可能循环!!这是潜在条件