Longest Increasing Path in a Matrix
Find the longest climb through a grid of numbers, one step up, down, left or right at a time, always to a larger number.
Given an m × n matrix of integers, with m rows and n columns, return the length of the longest increasing path in it. A path moves one cell at a time, up, down, left or right, never diagonally and never off the edge. Every step must go to a strictly larger value, and the length counts the cells on the path.
Example 1
Output: 4
Explanation: 1 → 2 → 6 → 9, starting at row 2, col 1 and climbing up col 0.
Example 2
Output: 4
Explanation: 3 → 4 → 5 → 6, along row 0 and down to row 1, col 2.
The Idea
Think of the matrix as a map of heights, like a hill drawn on squared paper with a number in each square. You walk from square to square, only up, down, left or right, and every step must climb to a higher number. How many squares can one walk cover?
In Example 1, start at the 1 in row 2, col 1. Its left neighbour holds 2, so step there. Above the 2 sits a 6 at row 1, col 0, and above that a 9 at row 0, col 0. Nothing next to that 9 is larger, so the walk stops after four cells. Equal numbers do not count as a climb: the 6 at row 1, col 0 cannot step right onto the other 6.
Every cell is a possible start, and from each cell a walk can branch in up to four directions. Trying every walk from every start repeats a lot of work. The walk from the 1 and the walk from the 2 both carry on through the same 6 and the same 9. So does the best walk from a cell depend on how we got there?
It does not. When the walk stands on the 2 at row 2, col 0, every cell behind it is smaller than 2, so it could never step back onto one of them anyway. The longest climb from the 2 is the same whether the walk started there or arrived from the 1. That gives a rule: the longest path starting at a cell is 1, for the cell itself, plus the longest path starting at its best larger neighbour. A cell with no larger neighbour gets 1.
The picture shows Example 1 twice. The left grid, labelled "the values", has the climb 1 → 2 → 6 → 9 marked in orange. The right grid, labelled "longest path starting here", holds the rule's number for every cell.
Follow the orange cells on the right, from the top. The 9 at row 0, col 0 has no larger neighbour, so it gets 1. The 6 below it gets 1 + 1 = 2, and the 2 below that gets 1 + 2 = 3. The 1 at row 2, col 1 has two larger neighbours: the 2 on its left, with 3, and the 6 above it, with 2. It takes the better one and gets 1 + 3 = 4.
The largest number in the right grid, 4, is the answer. So the whole problem comes down to one number per cell, each built from the numbers of its larger neighbours, and each worked out only once.
Solution Approach
Four questions shape the code: how one cell's number is worked out, how slow that is when nothing is saved, how to save each number, and whether a walk must remember the cells it has visited.
Working out one cell's number
How does the program apply the rule to one cell? A method, longestFromrc
The moves are tried in the order up, down, left, right. From the 1 at row 2, col 1, it goes up first, to the 6 at row 1, col 1, and from there up to the 9 at row 0, col 1. That climb ends with length 3. Only then does it back up and try the 2 on the left, which leads to the climb of 4. Following one climb as far as it goes before backing up to try another direction is called depth-first search, or DFS for short.
Trying every walk
What does this cost if every call starts from scratch? The calls for different start cells repeat each other. In Example 1 it hardly shows: a run that counts the calls gives 23 without saving anything, against 18 with saving. Now fill a 6 × 6 grid with row + col in each cell. Most cells then have two larger neighbours, the one below and the one to the right, and the number of different climbs grows very fast. The same count gives 3,382 calls for 6 × 6 and 705,310 for 10 × 10.
Saving each cell's number
How do we stop the repeats? Keep a table, memolongestFrommemo
In Example 1, the 9 at row 0, col 1 is a larger neighbour of both the 4 at row 0, col 2 and the 6 at row 1, col 1. Its number, 1, is worked out once, and both of them read it back from memo
Remembering visited cells
Walks through a grid often keep a set of visited cells, so they never go round in a circle. Does this one need it? No. Every step climbs to a larger value, so a walk can never return to a cell it has left: that cell's value is smaller than where the walk now stands. This rests on the check being "larger", not "larger or equal".
Java Solution
The method longestIncreasingPath
- First, it calls a helper,
, which creates the tablelongestFromEachCell with one entry per cell, all 0.memo - Inside the helper, two loops, one inside the other, visit every row
and every colr and callc on that cell, so every cell gets its number.longestFrom - The method
first checkslongestFrom . If it is not 0, the cell was worked out before, and the method returns the stored number.memo[r][c] - Otherwise it sets
to 1, for the cell on its own. Next it tries the four moves listed in the arraybest . Each move gives a neighbour's rowDIRS and colnr . For each neighbour inside the matrix with a larger value, it calls itself on that neighbour and keeps the larger ofnc and 1 plus the result.best - It writes
intobest and returns it.memo[r][c] - Back in
, a second pair of loops goes over the filledlongestIncreasingPath table and keeps its largest number in a variable namedmemo , which is the answer.longest
The mainmemo
import java.util.Arrays;
public class LongestIncreasingPathInMatrix {
// The four moves: up, down, left, right.
private static final int[][] DIRS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
public static int longestIncreasingPath(int[][] matrix) {
int[][] memo = longestFromEachCell(matrix);
int longest = 0;
for (int[] row : memo) {
for (int length : row) {
longest = Math.max(longest, length);
}
}
return longest;
}
static int[][] longestFromEachCell(int[][] matrix) {
int[][] memo = new int[matrix.length][matrix[0].length]; // 0 means not worked out yet
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++) {
longestFrom(matrix, r, c, memo);
}
}
return memo;
}
// Length of the longest increasing path that starts at row r, col c.
private static int longestFrom(int[][] matrix, int r, int c, int[][] memo) {
if (memo[r][c] != 0) {
return memo[r][c]; // worked out before: reuse it
}
int best = 1; // the cell on its own
for (int[] d : DIRS) {
int nr = r + d[0];
int nc = c + d[1];
if (nr >= 0 && nr < matrix.length && nc >= 0 && nc < matrix[0].length
&& matrix[nr][nc] > matrix[r][c]) { // a neighbour with a larger value
best = Math.max(best, 1 + longestFrom(matrix, nr, nc, memo));
}
}
memo[r][c] = best;
return best;
}
public static void main(String[] args) {
int[][] example1 = {{9, 9, 4}, {6, 6, 8}, {2, 1, 1}};
int[][] example2 = {{3, 4, 5}, {3, 2, 6}, {2, 2, 1}};
int[][] allSevens = {{7, 7}, {7, 7}};
int[][] oneCell = {{5}};
int[][] spiral = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}};
System.out.println("Example 1: " + longestIncreasingPath(example1));
System.out.println("Example 2: " + longestIncreasingPath(example2));
System.out.println("Longest path from each cell of Example 1:");
for (int[] row : longestFromEachCell(example1)) {
System.out.println(" " + Arrays.toString(row));
}
System.out.println("All sevens: " + longestIncreasingPath(allSevens));
System.out.println("One cell: " + longestIncreasingPath(oneCell));
System.out.println("Spiral 1 to 9: " + longestIncreasingPath(spiral));
}
}
Running it prints:
Example 1: 4
Example 2: 4
Longest path from each cell of Example 1:
[1, 1, 2]
[2, 2, 1]
[3, 4, 2]
All sevens: 1
One cell: 1
Spiral 1 to 9: 9
Look at the rows under "Longest path from each cell of Example 1": [1, 1, 2], [2, 2, 1] and [3, 4, 2]. They are the numbers in the right grid of the picture, and the 4 in the last row is where Example 1's answer of 4 comes from.
The line All sevens: 1[[5]][[1, 2, 3], [8, 9, 4], [7, 6, 5]]
The check really must be "larger" and not "larger or equal". A copy of longestFrom>=>[[7, 7]]StackOverflowErrormemo
Complexity
Each cell's number is worked out once, and every other call only reads memo
- Time: O(m × n), because
checks the four neighbours of each of the m × n cells only once, and every repeat call for a cell returns its stored number at once.longestFrom - Space: O(m × n), because
holds one number per cell, and the chain of calls waiting on each other can be as long as the longest path, which in the spiral covers all nine cells.memo
The same idea on a single row of numbers, where a step may jump ahead to any later larger number, is