求出一个矩阵中最长递增路径

本文探讨如何使用递归和深度优先遍历算法来解决寻找矩阵中最长递增路径的问题。通过递归遍历矩阵的每个元素,找到可能的最长路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

递归(深度优先遍历)

package Search;

import java.util.LinkedList;
import java.util.Stack;

public class LongestIncreasingPathInMatrix {
    /**
     * 寻找一个矩阵中最长增长路径
     * 深度搜索
     */
    public static int longestIncreasingInMatrix(int[][] matrix, LinkedList<Integer> list){
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return 0;
        }
        int max = 1;
        boolean[][] flag = new boolean[matrix.length][matrix[0].length];
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(!flag[i][j]){
                    LinkedList<Integer> tmp = new LinkedList<>();
                    int len = longest(matrix,i,j,tmp,flag);
                    if(len > max){
                        max = len;
                        while(!list.isEmpty()){
                            list.poll();
                        }
                        while(!tmp.isEmpty()) {
                            list.add(tmp.pollFirst());
                        }
                    }
                }
            }
        }
        return max == 1 ? 0 : max;

    }


   /* public static int longestIncreasing(int[][] matrix) {


    }*/
    public static int longest(int[][] matrix, int row, int col, LinkedList<Integer> list, boolean[][] flag){
        int[][] go = {{0,-1},{-1,0},{0,1},{1,0}};
        flag[row][col] = true;
        int max = 1;
        LinkedList<Integer> maxList = null;
        for(int i = 0; i < 4; i++){
            int newRow = row + go[i][0];
            int newCol = col + go[i][1];
            if(newRow >= 0 && newRow < matrix.length && newCol >= 0 && newCol < matrix[0].length
                    && matrix[newRow][newCol] > matrix[row][col]){
                LinkedList<Integer> tmp = new LinkedList<>();
                int ans = longest(matrix, newRow, newCol, tmp, flag);
                if(ans + 1 > max){
                    max = ans + 1;
                    maxList = tmp;
                }
            }
        }
        list.addLast(matrix[row][col]);
        if(maxList != null) {
            while (!maxList.isEmpty()) {
                list.addLast(maxList.pollFirst());
            }
        }
        return max;
    }
    public static void main(String[] args){
        int[][] arr = {
                       {13,33,32,89,90},
                       {14,34,24,23,91},
                       {13,14,103,102,101}
                       };
        LinkedList<Integer> list = new LinkedList<>();
        System.out.println(longestIncreasingInMatrix(arr,list));
        while(!list.isEmpty()){
            System.out.print(list.pollFirst() + " ");
        }
        System.out.println();
    }

}

 

### 矩阵最长递增路径算法实现 矩阵最长递增路径问题可以通过深度优先搜索(DFS)结合记忆化搜索来高效解决。以下是该问题的详细实现方法和代码示例。 #### 算法思路 1. 使用深度优先搜索(DFS)从每个单元格出发,寻找以当前单元格为起点的最长递增路径。 2. 为了避免重复计算,引入一个缓存矩阵 `memo`,存储已经计算过的单元格对应的最长递增路径长度。 3. 对于每个单元格 `(i, j)`,检查其上下左右四个方向的相邻单元格 `(x, y)`。如果满足 `matrix[x][y] > matrix[i][j]`,则递归调用 DFS 计算从 `(x, y)` 出发的最长递增路径,并更新当前单元格的路径长度。 4. 遍历整个矩阵,记录所有单元格的最长递增路径的最大值作为最终结果。 #### 实现代码 以下是使用 Python 实现的代码示例: ```python def longestIncreasingPath(matrix): if not matrix or not matrix[0]: return 0 m, n = len(matrix), len(matrix[0]) memo = [[-1 for _ in range(n)] for _ in range(m)] directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def dfs(i, j): if memo[i][j] != -1: return memo[i][j] max_length = 1 # 当前单元格本身的长度为1 for dx, dy in directions: x, y = i + dx, j + dy if 0 <= x < m and 0 <= y < n and matrix[x][y] > matrix[i][j]: length = 1 + dfs(x, y) max_length = max(max_length, length) memo[i][j] = max_length return max_length result = 0 for i in range(m): for j in range(n): result = max(result, dfs(i, j)) return result ``` #### 示例运行 以下是对示例输入的运行结果: **示例 1:** ```python matrix = [[9,9,4],[6,6,8],[2,1,1]] print(longestIncreasingPath(matrix)) # 输出:4 ``` **示例 2:** ```python matrix = [[3,4,5],[3,2,6],[2,2,1]] print(longestIncreasingPath(matrix)) # 输出:4 ``` **示例 3:** ```python matrix = [[1]] print(longestIncreasingPath(matrix)) # 输出:1 ``` #### 时间复杂度与空间复杂度 - **时间复杂度**:O(m * n),其中 `m` 和 `n` 分别是矩阵的行数和列数。每个单元格最多只会被访问一次[^3]。 - **空间复杂度**:O(m * n),用于存储缓存矩阵 `memo` 和递归调用栈的空间。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值