1
+ #include < iostream>
2
+ #include < vector>
3
+ #include < limits.h>
4
+ #include < queue>
5
+ using namespace std ;
6
+ int dx[] = { 1 ,0 };
7
+ int dy[] = { 0 ,1 };
8
+ vector<vector<int >>paths;
9
+ bool safe (vector<vector<int >>& mat, int i, int j) {
10
+ int n = mat.size ();
11
+ int m = mat[0 ].size ();
12
+ return (i < n and j < m and i >= 0 and j >= 0 and mat[i][j] != -1 );
13
+ }
14
+ void findPaths (vector<vector<int >>& mat, int i, int j, vector<int >& path) {
15
+ if (i == mat.size () - 1 and j == mat[0 ].size () - 1 ) {
16
+ path.push_back (mat[i][j]);
17
+ paths.push_back (path);
18
+ path.pop_back ();
19
+ return ;
20
+ }
21
+ if (!safe (mat, i, j)) return ;
22
+
23
+ int orig = mat[i][j];
24
+ path.push_back (orig);
25
+ mat[i][j] = -1 ;
26
+ for (int k = 0 ; k < 2 ; k++) {
27
+ int p = i + dx[k], q = j + dy[k];
28
+ findPaths (mat, p, q, path);
29
+ }
30
+ mat[i][j] = orig;
31
+ path.pop_back ();
32
+
33
+ }
34
+ // using Queue
35
+ class cell {
36
+ public:
37
+ int i, j;
38
+ vector<int > path;
39
+ cell (vector<int > p, int x, int y) {
40
+ path=p;
41
+ i = x;
42
+ j = y;
43
+ }
44
+ };
45
+
46
+ void findPaths (vector<vector<int >>& mat) {
47
+ int n = mat.size ();
48
+ int m = mat[0 ].size ();
49
+ vector<vector<int >>ans;
50
+ queue<cell> q;
51
+ q.push ({ {mat[0 ][0 ]}, 0 ,0 });
52
+ while (!q.empty ()){
53
+ auto p = q.front ();
54
+ q.pop ();
55
+ if (p.i ==n-1 and p.j ==m-1 ){
56
+ paths.push_back (p.path );
57
+ }
58
+ for (int k = 0 ; k < 2 ; k++) {
59
+ int x = p.i + dx[k], y = p.j + dy[k];
60
+ if (safe (mat, x, y)){
61
+ vector<int >temp= p.path ;
62
+ temp.push_back (mat[x][y]);
63
+ q.push ({temp,x,y});
64
+ temp.pop_back ();
65
+ }
66
+ }
67
+ }
68
+ }
69
+ int main () {
70
+ // input matrix with hurdles shown with number 0
71
+ vector<vector<int >> mat = {
72
+ {1 ,2 ,3 },{4 ,5 ,6 },{7 ,8 ,9 }
73
+ };
74
+ // find longest path with source (0, 0) and
75
+ // destination (1, 7)
76
+ int i = 0 , j = 0 ;
77
+ vector<int > path;
78
+ findPaths (mat, i, j, path);
79
+ findPaths (mat);
80
+
81
+ for (auto path : paths) {
82
+ for (auto val : path)
83
+ cout << val << " " ;
84
+ cout << endl;
85
+ }
86
+ return 0 ;
87
+ }
88
+ // https://leetcode.com/playground/QDwD9r84
0 commit comments