1
+ #include < iostream>
2
+ #include < vector>
3
+ #include < limits.h>
4
+ using namespace std ;
5
+ int dx[] = { 1 ,-1 ,0 ,0 };
6
+ int dy[] = { 0 ,0 ,1 ,-1 };
7
+ bool valid (vector<vector<int >>& mat, int i, int j) {
8
+ int n = mat.size ();
9
+ int m = mat[0 ].size ();
10
+ return (i < n and j < m and i >= 0 and j >= 0 and mat[i][j] == 1 );
11
+ }
12
+ pair<int , int > findLongestPath (vector<vector<int >>& mat, int i, int j, int x, int y) {
13
+ if (i == x and j == y) return { true , 0 }; // found with length 0
14
+ if (!valid (mat, i, j)) return { false , INT_MAX };
15
+
16
+ int ans = INT_MIN;
17
+
18
+ mat[i][j] = -1 ;
19
+ for (int k = 0 ; k < 4 ; k++) {
20
+ int p = i + dx[k], q = j + dy[k];
21
+ auto [found, length] = findLongestPath (mat, p, q, x, y);
22
+ if (found) ans = max (ans, length);
23
+ }
24
+ mat[i][j] = 1 ; // as 0 or -1 will not be visited again
25
+ if (ans == INT_MIN) return { false , INT_MAX };
26
+ return { true , 1 + ans };
27
+ }
28
+ int main () {
29
+ // input matrix with hurdles shown with number 0
30
+ vector<vector<int >> mat = {
31
+ { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 },
32
+ { 1 , 1 , 0 , 1 , 1 , 0 , 1 , 1 , 0 , 1 },
33
+ { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 }
34
+ };
35
+ // find longest path with source (0, 0) and
36
+ // destination (1, 7)
37
+ int i = 0 , j = 0 ;
38
+ int x = 1 , y = 7 ;
39
+ auto [found, length] = findLongestPath (mat, i, j, x, y);
40
+ cout << (found ? to_string (length) : " Not found\n " );
41
+ return 0 ;
42
+ }
43
+ // https://leetcode.com/playground/39yreovk
0 commit comments