Longest Increasing Path in a Matrix

LeetCode Q 329 - Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:
Input: nums = [ [9,9,4], [6,6,8], [2,1,1] ] Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums = [ [3,4,5], [3,2,6], [2,2,1] ] Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Solution :

DFS + Memorization
memo[i][j]: the maximum length of increasing numbers until point [i][j]

Code:

public int longestIncreasingPath(int[][] matrix) {
	if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;

	int m = matrix.length, n = matrix[0].length;
	int[][] memo = new int[m][n];
	booelan visited = new boolean[m][n];
	int[] directions = {0, 1, 0, -1, 0};

	int res = 0;
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			res = Math.max(res, dfs(matrix, i, j, memo, visited))
		}
	}

	return res;
}

private int dfs(int[][] matrix, int row, int col, int[][] memo, boolean[][] visited, int[] dirictions) {
	if (visited[row][col]) return memo[row][col];
	int m = matrix.length, n = matrix[0].length;

	int res = 1;
	for (int i = 0; i < 4; i++) {
		nx = row + directions[i];
		ny = col + directions[i];

		if (nx >= 0 && nx < m && ny >= 0 && ny < n && matrix[nx][ny] > matrix[x][y])
			res = Math.max(res, 1 + dfs(matrix, nx, ny, memo, visited, directions));
	}

	visited[x][y] = true;
	memo[x][y] = res;
	return res;
}

   Reprint policy


《Longest Increasing Path in a Matrix》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC