This problem looks busy at first, but the accepted solution is built around one steady invariant. For 329. Longest Increasing Path in a Matrix, the solution in this repository is mainly a DFS + memoization solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: DFS + memoization, graph traversal, stack.
The notes already sitting in the source point us in the right direction:
- DFS, iterative
- WA(because the visit order of children matters)
- 68 / 138 test cases passed.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are longestIncreasingPath, dfs.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The queue gives the solution a level-by-level or frontier-style traversal.
- The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//DFS, iterative
02//WA(because the visit order of children matters)
03//68 / 138 test cases passed.
04class Solution {
05public:
06 int longestIncreasingPath(vector<vector<int>>& matrix) {
07 int m = matrix.size();
08 if(m == 0) return 0;
09 int n = matrix[0].size();
10 if(n == 0) return 0;
11
12 vector<vector<int>> dirs = {{0,1}, {0,-1}, {1,0}, {-1,0}};
13
14 int ans = 0;
15
16 for(int i = 0; i < m; i++){
17 for(int j = 0; j < n; j++){
18 vector<vector<bool>> visited(m, vector(n, false));
19 stack<vector<int>> stk;
20
21 visited[i][j] = true;
22 stk.push({i, j, 1});
23
24 while(!stk.empty()){
25 vector<int> cur = stk.top(); stk.pop();
26 int ci = cur[0], cj = cur[1], cd = cur[2];
27
28 ans = max(ans, cd);
29
30 for(vector<int>& dir : dirs){
31 int ni = ci+dir[0];
32 int nj = cj+dir[1];
33
34 if(ni >= 0 && ni < m && nj >= 0 && nj < n){
35 if(!visited[ni][nj] && matrix[ni][nj] > matrix[ci][cj]){
36 visited[ni][nj] = true;
37 //depth plus 1
38 stk.push({ni, nj, cd+1});
39 }
40 }
41 }
42 }
43 }
44 }
45
46 return ans;
47 }
48};
49
50//DFS, recursive, memorization
51//https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/78308/15ms-Concise-Java-Solution
52//Runtime: 56 ms, faster than 39.66% of C++ online submissions for Longest Increasing Path in a Matrix.
53//Memory Usage: 12.6 MB, less than 90.91% of C++ online submissions for Longest Increasing Path in a Matrix.
54class Solution {
55public:
56 //the longest path starting from i, j
57 vector<vector<int>> cache;
58 vector<vector<int>> dirs;
59 vector<vector<int>> matrix;
60 int m, n;
61
62 int dfs(int i, int j){
63 if(cache[i][j] != 0) return cache[i][j];
64
65 int maxLen = 1;
66
67 for(vector<int>& dir : dirs){
68 int ni = i+dir[0];
69 int nj = j+dir[1];
70
71 if(ni >= 0 && ni < m && nj >= 0 && nj < n && matrix[ni][nj] > matrix[i][j]){
72 int curLen = 1 + dfs(ni, nj);
73 //try all 4 directions and choose the best one
74 maxLen = max(maxLen, curLen);
75 }
76 }
77
78 cache[i][j] = maxLen;
79
80 return maxLen;
81 }
82
83 int longestIncreasingPath(vector<vector<int>>& matrix) {
84 this->m = matrix.size();
85 if(m == 0) return 0;
86 this->n = matrix[0].size();
87 if(n == 0) return 0;
88
89 this->matrix = matrix;
90 cache = vector<vector<int>>(m, vector<int>(n, 0));
91 dirs = {{0,1}, {0,-1}, {1,0}, {-1,0}};
92
93 int ans = 0;
94
95 for(int i = 0; i < m; i++){
96 for(int j = 0; j < n; j++){
97 ans = max(ans, dfs(i, j));
98 }
99 }
100
101 return ans;
102 }
103};
104
105//BFS, Topological Sort
106//https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/288520/BFS-Implemented-Topological-Sort
107//Runtime: 168 ms, faster than 18.07% of C++ online submissions for Longest Increasing Path in a Matrix.
108//Memory Usage: 27.9 MB, less than 9.09% of C++ online submissions for Longest Increasing Path in a Matrix.
109class Solution {
110public:
111 int longestIncreasingPath(vector<vector<int>>& matrix) {
112 int m = matrix.size();
113 if(m == 0) return 0;
114 int n = matrix[0].size();
115 if(n == 0) return 0;
116
117 vector<vector<int>> dirs = {{0,1}, {0,-1}, {1,0}, {-1,0}};
118
119 vector<vector<int>> inDegree(m, vector(n, 0));
120
121 for(int i = 0; i < m; i++){
122 for(int j = 0; j < n; j++){
123 for(vector<int>& dir : dirs){
124 int ni = i + dir[0];
125 int nj = j + dir[1];
126 if(ni >= 0 && ni < m && nj >= 0 && nj < n && matrix[i][j] < matrix[ni][nj]){
127 //we create an edge from smaller to larger
128 inDegree[ni][nj]++;
129 }
130 }
131 }
132 }
133
134 queue<vector<int>> q;
135 for(int i = 0; i < m; i++){
136 for(int j = 0; j < n; j++){
137 if(inDegree[i][j] == 0){
138 q.push({i, j});
139 }
140 }
141 }
142
143 int ans = 0;
144
145 while(!q.empty()){
146 int levelCount = q.size();
147 //visite current level
148 while(levelCount-- > 0){
149 vector<int> cur = q.front(); q.pop();
150 int ci = cur[0], cj = cur[1];
151
152 for(vector<int>& dir : dirs){
153 int ni = ci+dir[0];
154 int nj = cj+dir[1];
155
156 if(ni >= 0 && ni < m && nj >= 0 && nj < n && matrix[ni][nj] > matrix[ci][cj] && --inDegree[ni][nj] == 0){
157 //if there's an edge from (ci,cj) to (ni,nj)
158 q.push({ni, nj});
159 }
160 }
161 }
162 ans++;
163 }
164
165 return ans;
166 }
167};
Cost