lelouche29

Jewels_&_maze_Samsung

Sep 12th, 2019
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. /*
  2. test cases
  3. 2
  4. 5
  5. 0 0 0 2 0
  6. 2 1 0 1 2
  7. 0 0 2 2 0
  8. 0 1 0 1 2
  9. 2 0 0 0 0
  10. 6
  11. 0 1 2 1 0 0
  12. 0 1 0 0 0 1
  13. 0 1 2 1 2 1
  14. 0 2 0 1 0 2
  15. 0 1 0 1 0 1
  16. 2 0 2 1 0 0
  17.  
  18. output:-
  19. 3 0 3 3 3
  20. 3 1 3 1 3
  21. 3 0 3 2 3
  22. 3 1 3 1 3
  23. 3 3 3 0 3
  24. 6
  25. 3 1 2 1 0 0
  26. 3 1 3 3 3 1
  27. 3 1 3 1 3 1
  28. 3 2 3 1 3 2
  29. 3 1 3 1 3 1
  30. 3 3 3 1 3 3
  31. 4
  32. */
  33.  
  34. #include <iostream>
  35. using namespace std;
  36.  
  37. int n;
  38. int mat[100][100];
  39. int sec[100][100];
  40. bool visited[199][100];
  41. int ans=-1;
  42.  
  43. bool canCheck(int x, int y){
  44.     if(x>=0 && x<n && y>=0 && y<n && mat[x][y]!=1 && visited[x][y]==false)
  45.         return true;
  46.     return false;
  47. }
  48.  
  49. void print(){
  50.     for(int i=0; i<n; i++){
  51.         for(int j=0; j<n; j++){
  52.             cout<<mat[i][j]<<" ";
  53.         }
  54.         cout<<endl;
  55.     }
  56.     cout<<endl;
  57. }
  58.  
  59. void solve(int x,int y,int jewels, int my_ans = 999999){
  60.     if(x==n-1 && y==n-1){
  61.         ans=max(ans,jewels);
  62.         if (ans == my_ans) print();
  63.         return;
  64.     }
  65.    
  66.     int dx[]={0,1,0,-1};
  67.     int dy[]={1,0,-1,0};
  68.  
  69.     for(int i=0; i<4; i++){
  70.         int m = x + dx[i];
  71.         int n = y+ dy[i];
  72.        
  73.         if(canCheck(m,n)){
  74.             visited[m][n]=true;
  75.  
  76.             if(mat[m][n]==2){
  77.                 mat[m][n]=3;
  78.                 solve(m,n,jewels +1, my_ans);
  79.             }
  80.             else {
  81.                 mat[m][n]=3;
  82.                 solve(m,n,jewels, my_ans);
  83.             }
  84.             visited[m][n]=false;
  85.             mat[m][n]=sec[m][n];
  86.         }
  87.     }
  88. }
  89.  
  90. int main() {
  91.     int t;
  92.     cin>>t;
  93.     while(t--){
  94.         cin>>n;
  95.  
  96.         ans=-1;
  97.         for(int i=0; i<n; i++)
  98.             for(int j=0; j<n; j++)
  99.                 cin>>mat[i][j];
  100.  
  101.         for(int i=0; i<n; i++)
  102.             for(int j=0; j<n; j++)
  103.                 sec[i][j] = mat[i][j];
  104.  
  105.         visited[10][10]={false};
  106.  
  107.         visited[0][0]=true;
  108.         mat[0][0]=3;
  109.        
  110.         solve(0,0,0); // statarting cordinates and no of jewels
  111.         cout<<ans<<endl;
  112.         int my_ans = ans;
  113.         ans = -1;
  114.         solve(0,0,0,my_ans);
  115.  
  116.     }
  117. }
Advertisement
Add Comment
Please, Sign In to add comment