Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Longest Increasing Path in a Matrix

Hard · Dynamic Programming · Asked at Google, Amazon, Meta, Microsoft

From any cell you may move up, down, left or right to a cell with a strictly larger value. Print the number of cells on the longest such path.

Input

First line: R C. Next R lines: C integers.

Output

The length of the longest increasing path.

Constraints

Strictly increasing moves can never form a cycle, so this is a longest path in a DAG. DFS with memoisation (best path starting at each cell) works; to avoid deep recursion, process cells in decreasing order of value: len[cell] = 1 + max(len of larger neighbours).

Example 1

Input

3 3
9 9 4
6 6 8
2 1 1

Output

4

Example 2

Input

3 3
3 4 5
3 2 6
2 2 1

Output

4

Hints

  1. Moving only to strictly larger values can never loop back — the moves form a DAG.
  2. The longest path from a cell depends only on its larger neighbours.
  3. Process cells from the largest value to the smallest, so neighbours are ready first.

Approach

Sort all cells by value in decreasing order. For each cell, len = 1 + max(len of the 4-neighbours with a strictly larger value) — those were processed earlier, so their lengths are final. Track the overall maximum. This is the same as DFS with memoisation but without recursion, which matters for snake-shaped inputs where the path can cover the whole grid.

Complexity: O(R · C · log(R · C)) time · O(R · C) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int R, C;
    cin >> R >> C;
    vector<vector<long long>> g(R, vector<long long>(C));
    vector<pair<long long, int>> cells;
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++) {
            cin >> g[i][j];
            cells.push_back({g[i][j], i * C + j});
        }
    sort(cells.rbegin(), cells.rend());
    vector<vector<int>> len(R, vector<int>(C, 1));
    int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}, best = 0;
    for (auto &c : cells) {
        int i = c.second / C, j = c.second % C;
        for (int d = 0; d < 4; d++) {
            int a = i + dx[d], b = j + dy[d];
            if (a >= 0 && b >= 0 && a < R && b < C && g[a][b] > g[i][j]) len[i][j] = max(len[i][j], len[a][b] + 1);
        }
        best = max(best, len[i][j]);
    }
    cout << best << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
R, C = data[0], data[1]
g = [data[2 + i * C : 2 + (i + 1) * C] for i in range(R)]
cells = sorted(((g[i][j], i, j) for i in range(R) for j in range(C)), reverse=True)
length = [[1] * C for _ in range(R)]
best = 0
for v, i, j in cells:
    cur = 1
    for a, b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
        if 0 <= a < R and 0 <= b < C and g[a][b] > v and length[a][b] + 1 > cur:
            cur = length[a][b] + 1
    length[i][j] = cur
    if cur > best:
        best = cur
print(best)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int R = (int) in.nval;
        in.nextToken();
        int C = (int) in.nval;
        long[][] g = new long[R][C];
        Integer[] cells = new Integer[R * C];
        for (int i = 0; i < R; i++)
            for (int j = 0; j < C; j++) {
                in.nextToken();
                g[i][j] = (long) in.nval;
                cells[i * C + j] = i * C + j;
            }
        Arrays.sort(cells, (x, y) -> Long.compare(g[y / C][y % C], g[x / C][x % C]));
        int[][] len = new int[R][C];
        int[] dx = {1, -1, 0, 0}, dy = {0, 0, 1, -1};
        int best = 0;
        for (int c : cells) {
            int i = c / C, j = c % C;
            len[i][j] = 1;
            for (int d = 0; d < 4; d++) {
                int a = i + dx[d], b = j + dy[d];
                if (a >= 0 && b >= 0 && a < R && b < C && g[a][b] > g[i][j]) len[i][j] = Math.max(len[i][j], len[a][b] + 1);
            }
            best = Math.max(best, len[i][j]);
        }
        System.out.println(best);
    }
}

Solve Longest Increasing Path in a Matrix online · All practice problems