Given an m×n integer matrix, return the length of the longest strictly increasing path, moving up, down, left or right.
Point an edge from each cell to every larger neighbor; the graph is a DAG. Repeatedly remove all cells with no smaller neighbors left (Kahn's algorithm). The number of layers peeled is the longest path.
1function longestIncreasingPath(matrix: number[][]): number {2const m = matrix.length, n = matrix[0].length, indeg = matrix.map((r) => r.map(() => 0));3const nbrs = (r: number, c: number) => [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]].filter(([x, y]) => x >= 0 && y >= 0 && x < m && y < n);4for (let r = 0; r < m; r++) for (let c = 0; c < n; c++)5for (const [x, y] of nbrs(r, c)) if (matrix[x][y] < matrix[r][c]) indeg[r][c]++;6let layer = [];7for (let r = 0; r < m; r++) for (let c = 0; c < n; c++) if (!indeg[r][c]) layer.push([r, c]);8let depth = 0;9while (layer.length) {10depth++;11const next = [];12for (const [r, c] of layer)13for (const [x, y] of nbrs(r, c)) if (matrix[x][y] > matrix[r][c] && --indeg[x][y] === 0) next.push([x, y]);14layer = next;15}16return depth;17}
| 9 | 9 | 4 |
| 6 | 6 | 8 |
| 2 | 1 | 1 |
| 1 | 2 | 0 |
| 1 | 1 | 3 |
| 1 | 0 | 0 |
Count each cell's smaller neighbors. Cells with none are local minima.
Space: play/pause · ←/→: step