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.
题目的大意就是给定一个数组,找出数字按递增排列的最长路径的长度。
这道题可以利用深搜的办法,给定一个起始点,对这个点四个方向的点做一次判断,若相邻的点比当前点大,那么就递归调用一次DepthFirst函数,得到以该相邻点为起始点的最大路径长度,然后比较四个相邻点的最大路径长度的最大值,取最大值加到当前点的最大路径长度中。
为了降低复杂度,需要使用两个辅助数组,一个数组是记录每个点的对应于以这个点为起点的最大路径长度,这个数组记为count,另一个数组b则是记录该点是否已经访问过,在调用递归函数之前,要先判断该点是否已经访问过,如果已经访问过就不需要再次调用函数了。
另外还要用一个变量maximum记录当前的最大长度,这样就不用在最后还要进行寻找最大值的操作。而且在主函数中要用一个两重循环来确定每一个点都被访问过。
这个算法是一个深度优先算法,所以时间复杂度为O(M*N).
还有一点需要特别注意的是,在传递数组的参数时,一定要记得将变量定义为引用类型,否则在每次调用函数时数组都要重新复制一次,我就是因为没有注意到这个问题,导致我在LeetCode上提交时超时了,找了很久才找到原因。
以下为源程序:
class Solution {
public:
int maximum=1,n,m;
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.size()==0) return 0;
n=matrix.size();
m=matrix[0].size();
vector<vector<bool> > b(n,vector<bool>(m,false));
vector<vector<int> > count(n,vector<int>(m,1));
DepthFirst(matrix,count,b,0,0);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(!b[i][j])
{
DepthFirst(matrix,count,b,i,j);
}
return maximum;
}
void DepthFirst(const vector<vector<int> >& matrix,vector<vector<int> >& count,vector<vector<bool> >& b,int i,int j)
{
int num=0;
b[i][j]=true;
if(i-1>=0&&matrix[i-1][j]>matrix[i][j])
{
if(!b[i-1][j]) DepthFirst(matrix,count,b,i-1,j);
if(count[i-1][j]>num) num=count[i-1][j];
}
if(j-1>=0&&matrix[i][j-1]>matrix[i][j])
{
if(!b[i][j-1]) DepthFirst(matrix,count,b,i,j-1);
if(count[i][j-1]>num) num=count[i][j-1];
}
if(i+1<n&&matrix[i+1][j]>matrix[i][j])
{
if(!b[i+1][j]) DepthFirst(matrix,count,b,i+1,j);
if(count[i+1][j]>num) num=count[i+1][j];
}
if(j+1<m&&matrix[i][j+1]>matrix[i][j])
{
if(!b[i][j+1]) DepthFirst(matrix,count,b,i,j+1);
if(count[i][j+1]>num) num=count[i][j+1];
}
count[i][j]+=num;
if(count[i][j]>maximum) maximum=count[i][j];
}
};
本文介绍了一种通过深度优先搜索解决二维矩阵中最长递增路径问题的方法。算法使用辅助数组记录每个点的最大路径长度,避免重复计算,并采用递归方式探索所有可能路径。
347

被折叠的 条评论
为什么被折叠?



