fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void solve()
  5. {
  6. int n;
  7. cin >> n;
  8.  
  9. vector<vector<int>> mat(n, vector<int> (n));
  10.  
  11. int l = 1, r = n*n;
  12.  
  13. for(int i = 0; i < n; i++)
  14. {
  15. if(i % 2 == 0)
  16. {
  17. for(int j = 0; j < n; j++)
  18. {
  19. if((i + j) % 2 == 0)
  20. mat[i][j] = l++;
  21. else
  22. mat[i][j] = r--;
  23. }
  24. }
  25. else
  26. {
  27. for(int j = n - 1; j >= 0; j--)
  28. {
  29. if((i + j) % 2 == 0)
  30. mat[i][j] = l++;
  31. else
  32. mat[i][j] = r--;
  33. }
  34. }
  35. }
  36.  
  37. for(int i = 0; i < n; i++)
  38. {
  39. for(int j = 0; j < n; j++)
  40. cout << mat[i][j] << " ";
  41. cout << endl;
  42. }
  43. }
  44.  
  45. int main() {
  46. // your code goes here
  47. int t;
  48. cin >> t;
  49.  
  50. while(t--)
  51. solve();
  52. }
Success #stdin #stdout 0s 5328KB
stdin
2
2
3
stdout
1 4 
3 2 
1 9 2 
7 3 8 
4 6 5