Advertisement
jasonpogi1669

Square Matrix Indices Tricks using C++

Feb 25th, 2022
877
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void Print(vector<vector<int>> a) {
  6.     for (int i = 0; i < (int) a.size(); i++) {
  7.         for (int j = 0; j < (int) a[i].size(); j++) {
  8.             cout << a[i][j] << " ";
  9.         }
  10.         cout << '\n';
  11.     }
  12.     cout << '\n';
  13. }
  14.  
  15. int main() {
  16.     ios::sync_with_stdio(false);
  17.     cin.tie(0);
  18.     // enter size of square matrix
  19.     int n;
  20.     cin >> n;      
  21.  
  22.     // upper-left right triangle:
  23.     vector<vector<int>> a(n, vector<int>(n, 0));
  24.     a[0][0] = 1;
  25.     for (int i = 1; i + 1 < n; i++) {
  26.         for (int j = i; j >= 0; j--) {
  27.             a[i - j][j] = 1;
  28.         }
  29.     }
  30.     Print(a);
  31.  
  32.     // bottom-right right triangle
  33.     a[n - 1][n - 1] = 1;
  34.     for (int j = n - 2; j > 0; j--) {
  35.         for (int i = 0; i < n - j; i++) {
  36.             a[n - 1 - i][j + i] = 1;
  37.         }
  38.     }
  39.     Print(a);
  40.    
  41.     // other diagonal
  42.     for (int i = n - 1; i >= 0; i--) {
  43.         a[i][n - 1 - i] = 1;
  44.     }
  45.     Print(a);
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement