[Leetcode] #329 Longest Increasing Path in a Matrix (DFS)

本文介绍了一个给定整数矩阵寻找最长递增路径的问题,并提供了一种解决方案。从任意单元格出发,可以移动到上下左右四个方向相邻的单元格,但不能斜向移动,也不能超出边界。文章通过深度优先搜索算法来解决此问题。

Discription:

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:

nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Solution:

int rows, cols;
vector<vector<int>> dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };

int dfs(vector<vector<int>>& matrix, int x, int y, vector<vector<int>> &path){
	if (path[x][y] != 0) return path[x][y];
	int maxLen = 1;
	for (int i = 0; i < dirs.size(); i++){
		int x1 = x + dirs[i][0], y1 = y + dirs[i][1];
		if (x1 >= 0 && x1 < rows && y1 >= 0 && y1<cols && matrix[x1][y1]>matrix[x][y]){
			int len = 1 + dfs(matrix, x1, y1, path);
			maxLen = max(len, maxLen);
		}
	}
	path[x][y] = maxLen;
	return maxLen;
}

int longestIncreasingPath(vector<vector<int>>& matrix) {
	if (matrix.empty())  return 0;
	rows = matrix.size();
	cols = matrix[0].size();
	vector<vector<int>> path(rows, vector<int>(cols, 0));
	int result = 1;
	for (int i = 0; i < rows; i++){
		for (int j = 0; j < cols; j++){
			int len = dfs(matrix, i, j, path);
			result = max(len, result);
		}
	}
	return result;
}
GitHub-Leetcode: https://github.com/wenwu313/LeetCode
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值