LeeCode (dfs) 329_ The longest incremental path in the matrix

LeeCode (dfs) 329_ The longest incremental path in the matrix

Problem:
Given an integer matrix, find the length of the longest incremental path.

For each cell, you can move up, down, left, and right. You cannot move in the diagonal direction or move outside the boundary (that is, no orbiting is allowed).

Example 1:

Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest incremental path is [1, 2, 6, 9].
Example 2:

Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest incremental path is [3, 4, 5, 6]. Note that it is not allowed to move in the diagonal direction.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving idea:
The problem-solving idea is similar to finding the longest path in a maze. You can use dfs to find the recursive result of each node.
But in this case, the efficiency is obviously too low and it takes too long. So you can use a matrix memo as a cache matrix to store the calculated cells. When this cell is accessed again, there is no need to calculate again, and the value is directly taken from memo.

Java code:


public class 矩阵中的最长递增路径 {
    
    
	//移动的方向的字典
	public int[][] dirs = {
    
    {
    
    0,1},{
    
    0,-1},{
    
    1,0},{
    
    -1,0}};
	public int rows,columns;
	
	public int longestIncreasingPath(int[][] matrix) {
    
    
		if( matrix == null || matrix.length == 0 || matrix[0].length==0 ){
    
    
			return 0;
		}
		
		rows = matrix.length;
		columns = matrix[0].length;
		
		//定义memo作为缓存矩阵
		int[][] memo = new int[rows][columns];
		
		//最长路径长度
		int ans = 0;
		
		for (int i = 0; i < rows; ++i) {
    
    
            for (int j = 0; j < columns; ++j) {
    
    
                ans = Math.max(ans, dfs(matrix, i, j, memo));
            }
        }

		return ans;
	}
	
	public int dfs(int[][] matrix, int row, int column, int[][] memo){
    
    
		//判断缓存中是否存在
		if(memo[row][column]!=0){
    
    
			return memo[row][column];
		}
		
		++memo[row][column];
		for(int dir[]:dirs){
    
    
			int newRow = row + dir[0];
			int newColumn = column + dir[1];
			//判断是否越界 && 下一个单元格的值大于当前值(即递增)
			if(newRow>=0 && newRow<rows && newColumn>=0 && newColumn<columns 
					&& matrix[newRow][newColumn] > matrix[row][column]){
    
    
				memo[row][column] = Math.max(memo[row][column],dfs(matrix, newRow, newColumn, memo) + 1);
			}
		}
        return memo[row][column];
	}
	
     
}

Guess you like

Origin blog.csdn.net/u013456390/article/details/112290965