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
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: 1 → 2 → 6 → 9, starting at row 2, col 1 and climbing up col 0.
Example 2
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: 3 → 4 → 5 → 6, along row 0 and down to row 1, col 2.
Solution

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.

Example 1 twice. Left, the values, with the uphill path 1, 2, 6, 9 from row 2, col 1 to row 0, col 0 marked in orange. Right, the longest path starting at each cell; along the orange path the numbers are 4, 3, 2, 1.

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, longestFrom, takes a row r and a col c and looks at that cell's four neighbours. For each neighbour that is inside the matrix and holds a larger value, it calls itself on that neighbour and adds 1. It keeps the largest result, or 1 when no neighbour is larger.

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, memo, with one entry per cell, all 0 at first. When longestFrom finishes a cell, it writes the number into memo, and any later call for that cell returns the stored number straight away. Every real number is at least 1, so 0 can safely mean "not worked out yet".

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. Saving each cell's number like this, so that no climb is worked out twice, is called memoization. With it, the 6 × 6 grid needs 96 calls and the 10 × 10 grid 280. For the 10 × 10 grid, that is one call for each of the 100 start cells plus one for each of the 180 uphill steps between neighbours.

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 works in these steps:

  1. First, it calls a helper, longestFromEachCell, which creates the table memo with one entry per cell, all 0.
  2. Inside the helper, two loops, one inside the other, visit every row r and every col c and call longestFrom on that cell, so every cell gets its number.
  3. The method longestFrom first checks memo[r][c]. If it is not 0, the cell was worked out before, and the method returns the stored number.
  4. Otherwise it sets best to 1, for the cell on its own. Next it tries the four moves listed in the array DIRS. Each move gives a neighbour's row nr and col nc. For each neighbour inside the matrix with a larger value, it calls itself on that neighbour and keeps the larger of best and 1 plus the result.
  5. It writes best into memo[r][c] and returns it.
  6. Back in longestIncreasingPath, a second pair of loops goes over the filled memo table and keeps its largest number in a variable named longest, which is the answer.

The main method runs both examples, prints the whole memo table for Example 1 row by row, and tries a grid of only 7s, a single cell, and a 3 × 3 spiral that climbs from 1 to 9.

Java
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:

Output
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 shows that equal neighbours never count as a step, so each 7 is a path of one cell. The single cell [[5]] also gives 1. The spiral [[1, 2, 3], [8, 9, 4], [7, 6, 5]] gives 9, because its climb runs round the edge and ends in the middle, through all nine cells.

The check really must be "larger" and not "larger or equal". A copy of longestFrom with >= in place of >, run on [[7, 7]], ends in a StackOverflowError. The first 7 calls the second, the second calls the first again, and neither ever reaches the line that writes its number into memo.

Complexity

Each cell's number is worked out once, and every other call only reads memo.

  • Time: O(m × n), because longestFrom 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.
  • Space: O(m × n), because memo 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.

The same idea on a single row of numbers, where a step may jump ahead to any later larger number, is Longest Increasing Subsequence.