[LeetCode][329. Longest Increasing Path in a Matrix] 4 Approaches: BFS, Memorization DFS, DP, Topo Sorting
By Long Luo
This article is the solution 4 Approaches: BFS, Memorization DFS, DP, Topo Sorting of Problem 329. Longest Increasing Path in a Matrix .
Here shows 4 Approaches to slove this problem: BFS, Memorization DFS, DP, Topological Sorting.
BFS
The simplest method that comes to my mind is BFS. We start search from each node, spread out like water, to see how far it can flood, and record the maximum flood path length of all nodes.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59class Solution {
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
if (row == 1 && col == 1) {
return 1;
}
int max = 1;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
max = Math.max(max, bfs(matrix, i, j));
}
}
return max;
}
public int bfs(int[][] matrix, int x, int y) {
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int ans = 0;
int row = matrix.length;
int col = matrix[0].length;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{x, y});
while (!queue.isEmpty()) {
int size = queue.size();
ans++;
for (int i = 0; i < size; i++) {
int[] curPos = queue.poll();
for (int[] dir : dirs) {
int nextX = curPos[0] + dir[0];
int nextY = curPos[1] + dir[1];
if (nextX < 0 || nextX >= row || nextY < 0 || nextY >= col) {
continue;
}
if (matrix[nextX][nextY] <= matrix[curPos[0]][curPos[1]]) {
continue;
}
queue.offer(new int[]{nextX, nextY});
}
}
}
return ans;
}
}
Analysis
- Time Complexity: \(O(m^2n^2)\).
- Space Complexity: \(O(mn)\).