fork(1) download
  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int maxer=INT_MIN;
  5. int visited[100][100];
  6.  
  7. int isvalid(int i,int j,int n)
  8. {
  9. if(i<0 || j<0 || i>=n || j>=n)
  10. return 0;
  11. else
  12. return 1;
  13. }
  14.  
  15. void fun_me(int arr[4][4], int m, int n,int i,int j,int steps,int cost)
  16. {
  17.  
  18. //cout<<steps<<endl;
  19. if(i>=n || j>=n)
  20. return;
  21. visited[i][j]=1;
  22. if(i==n-1 && steps==m-1)
  23. {
  24. if(maxer<arr[i][j]+cost)
  25. maxer=arr[i][j]+cost;
  26. //cout<<arr[i][j]+cost<<endl;
  27. }
  28.  
  29. if(isvalid(i+1,j,n) && !visited[i+1][j])
  30. fun_me(arr,m,n,i+1,j,steps+1,cost+arr[i][j]);
  31.  
  32. if(isvalid(i,j+1,n) && !visited[i][j+1])
  33. fun_me(arr,m,n,i,j+1,steps+1,cost+arr[i][j]);
  34.  
  35. if(isvalid(i,j-1,n) && !visited[i][j-1])
  36. fun_me(arr,m,n,i,j-1,steps+1,cost+arr[i][j]);
  37.  
  38. visited[i][j]=0;
  39. return ;
  40. }
  41. int main()
  42. {
  43. int arr[4][4]={{ 1 ,4 ,1 ,20 },
  44. { 5, 0,2,8 },
  45. { 6, 8,3,8 },
  46. { 3, 2,9,5 }};
  47.  
  48. int m,i,j,k;
  49.  
  50. for(i=0;i<100;i++)
  51. for(j=0;j<100;j++)
  52. {
  53. visited[i][j]=0;
  54. }
  55.  
  56. int n=4;
  57. cin>>m;
  58. fun_me(arr,m,4,0,0,0,0);
  59. cout<<maxer<<endl;
  60. return 0;
  61. }
Success #stdin #stdout 0s 3136KB
stdin
7
stdout
47