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 are not allowed).
Example 1:
Nums = [ [9, 9,4], [6, 6,8], [2,1, 1]]
Return4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
Nums = [ [3,4,5], [3,2,6], [2,2,1]
Return4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
classSolution { Public: BOOLCheckrange (vector<vector<int> >& Matrix,intXinty) {intn = matrix.size (), M = matrix[0].size (); if(X <0|| Y <0|| X >= N | | Y >= m)return false; return true; } intDFS (vector<vector<int> >& Matrix, vector<vector<int> >& DP, vector<vector<BOOL> >& Vis, vector<vector<int> >& dir,intXinty) {if(Dp[x][y])returnDp[x][y]; intMAX =-1; for(intI=0; I<dir.size (); ++i) {intNX = x + dir[i][0], NY = y + dir[i][1]; if(Checkrange (Matrix, NX, NY) &&!vis[nx][ny] && Matrix[nx][ny] >Matrix[x][y]) {Vis[nx][ny]=true; MAX= MAX (max, DFS (Matrix, DP, Vis, DIR, NX, NY) +1); Vis[nx][ny]=false; } } if(MAX = =-1)return 1; Dp[x][y]=MAX; returnDp[x][y]; } intLongestincreasingpath (vector<vector<int>>&matrix) { intn =matrix.size (); if(n = =0)return 0; intm = matrix[0].size (); Vector<vector<int> > DP (N, vector<int> (M,0)); Vector<vector<BOOL> > Vis (N, vector<BOOL> (M,false)); Vector<vector<int> > Dir (4); dir[0].push_back (-1); dir[0].push_back (0); dir[1].push_back (0); dir[1].push_back (1); dir[2].push_back (1); dir[2].push_back (0); dir[3].push_back (0); dir[3].push_back (-1); intres =-1; for(intI=0; i<n; ++i) { for(intj=0; j<m; ++j) {Vis[i][j]=true; DP[I][J]=DFS (Matrix, DP, Vis, dir, I, J); Res=Max (res, dp[i][j]); VIS[I][J]=false; } } returnRes; }};
[email protected] [329] Longest increasing Path in a Matrix (DFS + memory Search)