解法很简单,遍历求解每个元素的最长深度,有点类似图的深度遍历算法,但是还是有些不同,
另外,需要有个中间表用来记录已经计算过的节元素的深度,提高运行效率, 算法并不是最优的,比如说,如果某个节点计算过了就不要重复计算了
#include <iostream>
#include <vector>
using namespace std;
void Output(const vector<vector<int> > & vecMatrix)
{
for (auto itr=vecMatrix.begin();
itr!=vecMatrix.end();
++itr)
{
for (auto itr2=itr->begin();
itr2!=itr->end();
++itr2)
{
cout << *itr2 << " ";
}
cout << endl;
}
}
void CalculateLength(const vector<vector<int> > & vecMatrix,
vector<vector<int> > & vecLength,
int i,
int j,
int R,
int C)
{
int nLeft = 0;
int nRight = 0;
int nTop = 0;
int nDown = 0;
if (j-1 >= 0 && vecMatrix[i][j-1] < vecMatrix[i][j]) {
if (vecLength[i][j-1] == 0) {
CalculateLength(vecMatrix, vecLength, i, j-1, R, C);
}
nLeft = vecLength[i][j-1];
}
if (j+1 < C && vecMatrix[i][j+1] < vecMatrix[i][j]) {
if (vecLength[i][j+1] == 0) {
CalculateLength(vecMatrix, vecLength, i, j+1, R, C);
}
nRight = vecLength[i][j+1];
}
if (i-1 >= 0 && vecMatrix[i-1][j] < vecMatrix[i][j]) {
if (vecLength[i-1][j] == 0) {
CalculateLength(vecMatrix, vecLength, i-1, j, R, C);
}
nTop = vecLength[i-1][j];
}
if (i+1 < R && vecMatrix[i+1][j] < vecMatrix[i][j]) {
if (vecLength[i+1][j] == 0) {
CalculateLength(vecMatrix, vecLength, i+1, j, R, C);
}
nDown = vecLength[i+1][j];
}
int nMax = nLeft;
nMax = nMax < nRight ? nRight : nMax;
nMax = nMax < nTop ? nTop : nMax;
nMax = nMax < nDown ? nDown : nMax;
vecLength[i][j] = nMax + 1;
}
int CalculateMaxLength(const vector<vector<int> > & vecMatrix)
{
vector<vector<int> > vecLength;
int R = vecMatrix.size();
int C = vecMatrix[0].size();
for (int i=0; i<R; ++i) {
vector<int> vecTmp(C, 0);
vecLength.push_back(vecTmp);
}
for (int i=0; i<R; ++i)
{
for (int j=0; j<C; ++j)
{
CalculateLength(vecMatrix, vecLength, i, j, R, C);
}
}
int nMaxLength = 0;
for (int i=0; i<R; ++i)
{
for (int j=0; j<C; ++j)
{
nMaxLength = nMaxLength < vecLength[i][j] ? vecLength[i][j] : nMaxLength;
}
}
return nMaxLength;
}
int main(int argc, char ** argv)
{
vector<vector<int> > vecMatrix;
vector<int> vecTmpNum;
vecTmpNum.resize(5);
vecTmpNum[0] = 1;
vecTmpNum[1] = 2;
vecTmpNum[2] = 3;
vecTmpNum[3] = 4;
vecTmpNum[4] = 5;
vecMatrix.push_back(vecTmpNum);
vecTmpNum[0] = 16;
vecTmpNum[1] = 17;
vecTmpNum[2] = 18;
vecTmpNum[3] = 19;
vecTmpNum[4] = 6;
vecMatrix.push_back(vecTmpNum);
vecTmpNum[0] = 15;
vecTmpNum[1] = 24;
vecTmpNum[2] = 25;
vecTmpNum[3] = 20;
vecTmpNum[4] = 7;
vecMatrix.push_back(vecTmpNum);
vecTmpNum[0] = 14;
vecTmpNum[1] = 23;
vecTmpNum[2] = 22;
vecTmpNum[3] = 21;
vecTmpNum[4] = 8;
vecMatrix.push_back(vecTmpNum);
vecTmpNum[0] = 13;
vecTmpNum[1] = 12;
vecTmpNum[2] = 11;
vecTmpNum[3] = 10;
vecTmpNum[4] = 9;
vecMatrix.push_back(vecTmpNum);
Output(vecMatrix);
cout << "MaxLength:" << CalculateMaxLength(vecMatrix) << endl;;
return 0;
}
网友评论