Skip to content

Commit 64b2c95

Browse files
Update Longest_Increasing_Path_in_a_Matrix.cpp
1 parent 099bd28 commit 64b2c95

File tree

1 file changed

+58
-1
lines changed

1 file changed

+58
-1
lines changed

Longest Increasing Path in a Matrix/Longest_Increasing_Path_in_a_Matrix.cpp

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,61 @@ class Solution
9494
}
9595
return res;
9696
}
97-
};
97+
};
98+
99+
// 另外一种思路是使用带有备忘录的DFS
100+
101+
// Runtime: 36 ms, faster than 95.05% of C++ online submissions for Longest Increasing Path in a Matrix.
102+
// Memory Usage: 12.5 MB, less than 96.96% of C++ online submissions for Longest Increasing Path in a Matrix.
103+
104+
class Solution
105+
{
106+
public:
107+
int longestIncreasingPath(vector<vector<int>>& matrix)
108+
{
109+
// 边界条件处理
110+
rows = matrix.size();
111+
if (rows == 0) return 0;
112+
113+
cols = matrix[0].size();
114+
if (cols == 0) return 0;
115+
116+
vector<vector<int>> memo(rows, vector<int>(cols, 0));
117+
118+
int res = 1;
119+
for (int i = 0; i < rows; ++i)
120+
{
121+
for (int j = 0; j < cols; ++j)
122+
{
123+
memo[i][j] = dfs(matrix, memo, i ,j);
124+
res = max(res, memo[i][j]);
125+
}
126+
}
127+
return res;
128+
}
129+
private:
130+
int rows, cols;
131+
private:
132+
int dfs(vector<vector<int>>& matrix, vector<vector<int>>& memo, int i, int j)
133+
{
134+
if (memo[i][j] == 0)
135+
{
136+
int maxLength = 1;
137+
int offseti[] = {-1, 1 ,0, 0};
138+
int offsetj[] = {0 ,0, -1, 1};
139+
140+
for (int k = 0; k < 4; ++k)
141+
{
142+
int x = i + offseti[k];
143+
int y = j + offsetj[k];
144+
if (x >= 0 && x < rows && y >= 0 && y < cols && matrix[x][y] > matrix[i][j])
145+
{
146+
maxLength = max(dfs(matrix, memo, x, y) + 1, maxLength);
147+
}
148+
}
149+
150+
memo[i][j] = maxLength;
151+
}
152+
return memo[i][j];
153+
}
154+
};

0 commit comments

Comments
 (0)