Leetcode 329. Longest Increasing Path in a Matrix

本文探讨了在整数矩阵中寻找最长递增路径的问题,提供了两种解决方案:一是结合深度优先搜索(DFS)与动态规划(DP)的方法,二是利用拓扑排序的思想,通过计算每个节点的入度并运用广度优先搜索(BFS)来解决问题。

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

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).
在这里插入图片描述

method 1 DFS+dp

直接使用DFS会超时,所以将想到使用dp,并且递增序列已经严格限制了点的顺序,这样就防止重复计算dp数组,只有该点位置的值小于(大于)邻近的值,才能在对应的dp上加1,最后四个方向计算完毕后取最大的。

int maxLength = 1;

int helper(vector<vector<int>>& matrix, int i, int j, vector<vector<int>>& dp){
	if (dp[i][j] != 0) return dp[i][j];
    int dirc[] = { 0, 1, 0, -1, 0 };
	int m = matrix.size(), n = matrix[0].size();
	int curLength = 1;
	for (int k = 0; k < 4; k++)
	{
		int x = i + dirc[k], y = j + dirc[k + 1];
		if (x >= 0 && y >= 0 && x < m && y < n && matrix[i][j] < matrix[x][y]){
			int dist = 1 + helper(matrix, x, y, dp);
			curLength = max(dist, curLength);
		}
	}

	dp[i][j] = curLength;
	return curLength;
}

int longestIncreasingPath(vector<vector<int>>& matrix) {
	if (matrix.size() == 0) return 0;
	int m = matrix.size();
	int n = matrix[0].size();

	vector<vector<int>> dp;
	for (int i = 0; i < m; i++)
	{
		vector<int> vec;
		for (int j = 0; j < n; j++)
		{
			vec.push_back(0);
		}
		dp.push_back(vec);
	}

	for (int i = 0; i < matrix.size(); i++)
	{
		for (int j = 0; j < matrix[i].size(); j++)
		{
			maxLength = max(maxLength, helper(matrix, i, j, dp));
		}
	}

	return maxLength;
}

method 2 topological sort

本题可以抽象为一个DAG,method 1表现得正是DAG上的动态规划。
本题所求的可以看作DAG上的一个最长递增序列,正因为严格递增的关系,所以可以使用拓扑排序。使用拓扑排序,那么就要计算各点的入度,这里规定点(x,y)附近值比(x,y)更大的点的个数为其入度
使用BFS进行拓扑排序,使用一个length记录拓扑排序后序列的长度。当入度为0时,将新的点压入队列

    public int longestIncreasingPath(int[][] matrix) {
        // Corner cases
        if (matrix.length == 0) {
            return 0;
        }
        
        int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        int rows = matrix.length, cols = matrix[0].length;
        
        // indegree[i][j] indicates thee number of adjacent cells bigger than matrix[i][j]
        int[][] indegree = new int[rows][cols];
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                for (int[] dir: dirs) {
                    int nx = x + dir[0];
                    int ny = y + dir[1];
                    if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {
                        if (matrix[nx][ny] > matrix[x][y]) {
                            indegree[x][y]++;
                        }
                    }
                }
                
            }
        }
        
        // Add each cell with indegree zero to the queue
        Queue<int[]> queue = new LinkedList<>();
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                if (indegree[x][y] == 0) {
                    queue.offer(new int[]{x, y});
                }
            }
        }
        
        int length = 0; // The longest path so far
        // BFS implements the Topological Sort
        while(!queue.isEmpty()) {
            int sz = queue.size();
            for (int i = 0; i < sz; i++) {
                int[] cur = queue.poll();
                int x = cur[0];
                int y = cur[1];
                for (int[] dir: dirs) {
                    int nx = x + dir[0];
                    int ny = y + dir[1];
                    if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {
                        if (matrix[nx][ny] < matrix[x][y] 
                            && --indegree[nx][ny] == 0) {
                           queue.offer(new int[]{nx, ny});
                        }
                    }
                }
            }
            length++;
        }
        
        return length;
    }

summary

  1. 建立将问题抽象为DAG的抽象思维
  2. 当所求的解具有严格的顺序,考虑使用BFS求拓扑排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值