fork download
  1. // Program to Print All Possible Paths from Top Left to Bottom Right of a Matrix
  2.  
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. void printVector(vector<int> &v){
  7. for(auto it:v){
  8. cout<<it<<" ";
  9. }
  10. cout<<"\n";
  11. }
  12.  
  13. void printPaths(int mat[][3], vector<int> &v, int i, int j, int n, int m){
  14.  
  15. if(i > n || j > m) return;
  16.  
  17. if(i==n && j==m){
  18. printVector(v);
  19. return;
  20. }
  21.  
  22. v.push_back(mat[i][j]);
  23.  
  24. printPaths(mat,v,i+1,j,n,m);
  25. printPaths(mat,v,i,j+1,n,m);
  26.  
  27. v.pop_back();
  28. }
  29.  
  30. void printPathUtil(int mat[][3], int n, int m){
  31.  
  32. vector<int> v;
  33. printPaths(mat,v,0,0,n,m);
  34. }
  35.  
  36. int main(){
  37.  
  38. int mat[3][3]={
  39. {1,2,3},
  40. {4,5,6},
  41. {7,8,9}
  42. };
  43.  
  44. int n=3,m=3;
  45.  
  46. printPathUtil(mat,n-1,m-1);
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1 4 7 8 
1 4 5 8 
1 4 5 6 
1 2 5 8 
1 2 5 6 
1 2 3 6