Topic Links:http://www.lintcode.com/zh-cn/problem/longest-increasing-continuous-subsequence-ii/Longest ascending continuous sub-sequence II given an integer matrix (where there are n rows, m columns), find the longest ascending continuous subsequence in the matrix. (The longest ascending continuous subsequence can be started from any row or any column, moving up/down/left/right in any direction).
Sample Example
Given a matrix
[ [1 ,2 ,3 ,4 ,5], [16,17,24,23,6], [15,18,25,22,7], [14,19,20,21,8], [13,12,11,10,9]]
Return25
Idea: Memory Search + DP
Set LICs (num) indicates the length of the longest ascending subsequence sequence starting with num, then LICs (a[x][y]) = Max (LICs (a[x-1][y)), LICs (a[x][y-1), LICs (X+1,y), LICs (x, y+1) +1;
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<vector>#include<deque>#include<map>using namespacestd;classSolution { Public: /** * @param A an integer matrix * @return an integer*/ intN, M, MaxL; intlics[ +][ +]; intvis[ +][ +]; intdir[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}}; intDFS (vector<vector<int>>& A,intXinty) { intMaxlics =0; Vis[x][y]=1; for(intI=0; i<4; ++i) { intxx = x+dir[i][0]; intyy = y+dir[i][1]; if(xx<0|| yy<0|| Xx>=n | | YY>=M)Continue; if(A[x][y] >= A[xx][yy])Continue; if(!Vis[xx][yy]) maxlics=Max (Maxlics, DFS (A, XX, yy)); ElseMaxlics=Max (Maxlics, Lics[xx][yy]); } Lics[x][y]= maxlics+1; if(MaxL < lics[x][y]) MaxL =Lics[x][y]; returnLics[x][y]; } intLongestincreasingcontinuoussubsequenceii (vector<vector<int>>&A) {n=a.size (); if(n = =0)return 0; M= a[0].size (); memset (LICs,0,sizeof(LICs)); memset (Vis,0,sizeof(VIS)); MaxL=0; for(intI=0; i<n; ++i) for(intj=0; j<m; ++j)if(!Vis[i][j]) DFS (A, I, J); returnMaxL; }};/*1 2 3 4 516 615 (714), 813 9*/
Lintcode Longest ascending continuous sub-sequence II (two-dimensional longest ascending continuous sequence)