Ankit_132

D

Dec 27th, 2023
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1.  
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. #define _test   int _TEST; cin>>_TEST; while(_TEST--)
  7.  
  8. int main()
  9. {
  10.     _test
  11.     {
  12.         int n;
  13.         cin>>n;
  14.  
  15.         if(n==2)
  16.         {
  17.             cout<<-1<<"\n";
  18.             continue;
  19.         }
  20.  
  21.         vector<vector<int>> ans(n, vector<int> (n));
  22.  
  23.         if(n%2)
  24.         {
  25.             for(int i=0, k=1; i<n; i++)
  26.             {
  27.                 for(int j=0; j<n; j++)
  28.                     ans[i][j] = k++;
  29.             }
  30.  
  31.             for(int j=1; j<n; j+=2)
  32.                 swap(ans[1][j], ans[1][j+1]);
  33.         }
  34.         else
  35.         {
  36.             int k = 1;
  37.             for(int i=0; i<n-1; i++)
  38.             {
  39.                 for(int j=0; j<n-1; j++)
  40.                     ans[i][j] = k++;
  41.             }
  42.  
  43.             for(int j=1; j<n-1; j+=2)
  44.                 swap(ans[1][j], ans[1][j+1]);
  45.  
  46.             for(int i=0; i<n; i++)
  47.                 ans[i][n-1] = k++;
  48.  
  49.             for(int j=n-2; j>=0; j--)
  50.                 ans[n-1][j] = k++;
  51.                
  52.             swap(ans[n-2][0], ans[n-2][1]);
  53.         }
  54.  
  55.         for(auto e: ans)
  56.         {
  57.             for(auto x: e)
  58.                 cout<<x<<" ";
  59.             cout<<"\n";
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment