Skip to content

Add files via upload #290

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions C++/Find_the_longest_path_in_a_matrix_with_given_constraints.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// C++ program to find the longest path in a matrix

#include <bits/stdc++.h>
#define n 3
using namespace std;


int findLongestFromACell(int i, int j, int mat[n][n],
int dp[n][n])
{
if (i < 0 || i >= n || j < 0 || j >= n)
return 0;


if (dp[i][j] != -1)
return dp[i][j];

int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN;

if (j < n - 1 && ((mat[i][j] + 1) == mat[i][j + 1]))
x = 1 + findLongestFromACell(i, j + 1, mat, dp);

if (j > 0 && (mat[i][j] + 1 == mat[i][j - 1]))
y = 1 + findLongestFromACell(i, j - 1, mat, dp);

if (i > 0 && (mat[i][j] + 1 == mat[i - 1][j]))
z = 1 + findLongestFromACell(i - 1, j, mat, dp);

if (i < n - 1 && (mat[i][j] + 1 == mat[i + 1][j]))
w = 1 + findLongestFromACell(i + 1, j, mat, dp);

return dp[i][j] = max({x, y, z, w, 1});
}


int finLongestOverAll(int mat[n][n])
{
int result = 1; // Initialize result


int dp[n][n];
memset(dp, -1, sizeof dp);

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dp[i][j] == -1)
findLongestFromACell(i, j, mat, dp);

// Update result if needed
result = max(result, dp[i][j]);
}
}

return result;
}


int main()
{
int mat[n][n]
= { { 1, 2, 9 }, { 5, 3, 8 }, { 4, 6, 7 } };
cout << "Length of the longest path is "
<< finLongestOverAll(mat);
return 0;
}