Leetcode之 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.

代码:

class Solution {
public:
  int length = INT_MIN;
vector<vector<int>> directions = { {0,1},{0,-1},{1,0},{-1,0} };

int helper(vector<vector<int>>& records,vector<vector<int>>& matrix, int x, int y, int l) {
	if (records[x][y] != 0)return records[x][y];
	
	//length = max(length, l);
	for (int i = 0; i < directions.size(); i++) {
		int hx = x + directions[i][0];
		int hy = y + directions[i][1];
		if (hx<0 || hy<0 || hx>=matrix.size() || hy>=matrix[0].size())continue;
		if (matrix[hx][hy] <= matrix[x][y])continue;

		if (records[hx][hy] != 0) {
			records[x][y] = max(records[x][y], records[hx][hy] + 1);
		}
		else {
			int temp = matrix[x][y];
			matrix[x][y] = 0;
			records[x][y]=max(records[x][y],helper(records, matrix, hx, hy, l + 1)+1);
			matrix[x][y] = temp;
		}
		
	}
	return records[x][y];
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
	int h = matrix.size();
	if (h == 0)return 0;
	int w = matrix[0].size();
	if (w == 0)return 0;

	vector<vector<int>> records(h, vector<int>(w, 0));
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w; j++) {
			length=max(length,helper(records,matrix, i, j, 1));
		}
	}
	return length+1;
}
};

思路:

记忆化搜索+DFS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值