Given M * N matrix of characters, find the length of the longest path in the matrix starting from the given source.
Note : All characters in the longest path should be increasing and consecutive to each other in alphabetical order. We are allowed to search the next character in all 8 directions.
I have correctly found out the length of the sequence but there is a problem in path. path is not correct.
Here is my code
#include<iostream>
#include<vector>
using namespace std;
//Below array details all 8 posible directions
int row[] = { -1,-1,-1, 0, 0, 1, 1, 1 };
int col[] = { 1, 0, -1, 1,-1, -1,0, 1 };
int length(char arr[][5], int x, int y, char previous, vector<pair<int,int> > &path, int k)
{
// x and y must be bounded between 0 to 4
if( x < 0 || x > 4 || y > 4 || y < 0)
return 0;
int l = 0;
int max_length = 0;
for( int i = 0; i < 8; i++)
{
// storing next character in search
char ch = arr[x+row[i]][y+col[i]];
//checking whether ch is the next character in the sequence or not
if(ch == previous + 1)
{
//if k != path.size() then we have taken back in
// the sequence so no need to push back character in the path
if(k == path.size())
{
// Pushing co-ordinates of next valid character
path.push_back(make_pair(x+row[i], y+col[i]));
}
else
path.pop_back();
l = 1 + length(arr, x+row[i], y+ col[i], ch , path, ++k);
max_length = max( l, max_length);
}
}
return max_length;
}
int main()
{
char arr[5][5] = {
{ 'd','e','h','x','b'},
{ 'a','o','g','p','e'},
{ 'd','d','c','f','d'},
{ 'e','b','e','a','s'},
{ 'c','d','y','e','n'}
};
vector<pair<int,int> > path;
//Pusing source address
path.push_back(make_pair(2,2));
int k = 1;
int Len = length(arr, 2, 2 , arr[2][2], path, k);
cout << "Length of the Longest sequence is : " << Len + 1 <<endl;
//printing the path
cout << "Path is : "<<endl;
for( pair<int,int> i : path)
{
cout <<"( " << i.first <<","<<i.second <<" )" ;
}
return 0;
}
Actual output :
Length of the Longest sequence is : 6
Path is
( 2,2 )( 2,1)( 3,0 )( 3,2 )( 2,3 )( 1,2 )( 0,2 )
Expected output
Length of the Longest sequence is : 6
Path is
( 2,2 )(2,1 )( 3,2 )( 2,3 )( 1,2 )( 0,2 )
There is a extra (3,0) in my output. When I take back from (3,0) , I could not pop it.
Any help will be appreciated.
Aucun commentaire:
Enregistrer un commentaire