// Online C++ compiler to run C++ program online
#include <iostream>
#include<bits/stdc++.h>
#include <iomanip>
using namespace std;
int main() {
int n;
std::cout << "Enter the value of n: ";
cin >> n;
vector<vector<int>> matrix(n, vector<int>(n, 0));
int num = 1,start=0,j=0;
int limit=(n-1)/2;
bool check=false;
int per_row=(n-1)/2;
if(n%2==1){
limit=2;
check=false;
per_row=2;
}else{
limit=2;
check=true;
per_row=1;
}
for (int i = n - 1; i >= 0; i--) {
check=!check;
if(check){
j=n-1;
}else{
j=start;
}
while(true) {
if(j<start||j==n)break;
if(check){
matrix[i][j]=num++;
j--;
}else{
matrix[i][j]=num++;
j++;
}
}
if(per_row==limit){
start+=2;
per_row=0;
}
per_row++;
if(start>=n)break;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0)
std::cout << std::setw(3) << " " << "\t";
else
std::cout << std::setw(3) << matrix[i][j] << "\t";
}
std::cout << std::endl;
}
return 0;
}
Ly8gT25saW5lIEMrKyBjb21waWxlciB0byBydW4gQysrIHByb2dyYW0gb25saW5lCiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KI2luY2x1ZGUgPGlvbWFuaXA+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmludCBtYWluKCkgewogIGludCBuOwogICAgc3RkOjpjb3V0IDw8ICJFbnRlciB0aGUgdmFsdWUgb2YgbjogIjsKICAgIGNpbiA+PiBuOwoKICAgIHZlY3Rvcjx2ZWN0b3I8aW50Pj4gbWF0cml4KG4sIHZlY3RvcjxpbnQ+KG4sIDApKTsKCiAgICBpbnQgbnVtID0gMSxzdGFydD0wLGo9MDsKICAgIGludCBsaW1pdD0obi0xKS8yOwogICAgYm9vbCBjaGVjaz1mYWxzZTsKICAgIGludCBwZXJfcm93PShuLTEpLzI7CiAgICBpZihuJTI9PTEpewogICAgICAgIGxpbWl0PTI7CiAgICAgICAgY2hlY2s9ZmFsc2U7CiAgICAgICAgcGVyX3Jvdz0yOwogICAgfWVsc2V7CiAgICAgICAgbGltaXQ9MjsKICAgICAgICBjaGVjaz10cnVlOwogICAgICAgIHBlcl9yb3c9MTsKICAgIH0KICAgIAogICAgZm9yIChpbnQgaSA9IG4gLSAxOyBpID49IDA7IGktLSkgewogICAgICAgIGNoZWNrPSFjaGVjazsKICAgICAgICAKICAgICAgICBpZihjaGVjayl7CiAgICAgICAgICAgIGo9bi0xOwogICAgICAgIH1lbHNlewogICAgICAgICAgICBqPXN0YXJ0OwogICAgICAgIH0KICAgICAgICB3aGlsZSh0cnVlKSB7CiAgICAgICAgICAgIGlmKGo8c3RhcnR8fGo9PW4pYnJlYWs7CiAgICAgICAgICAgIGlmKGNoZWNrKXsKICAgICAgICAgICAgICAgIG1hdHJpeFtpXVtqXT1udW0rKzsKICAgICAgICAgICAgICAgIGotLTsKICAgICAgICAgICAgfWVsc2V7CiAgICAgICAgICAgICAgICBtYXRyaXhbaV1bal09bnVtKys7CiAgICAgICAgICAgICAgICBqKys7CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAgaWYocGVyX3Jvdz09bGltaXQpewogICAgICAgICAgICBzdGFydCs9MjsKICAgICAgICAgICAgcGVyX3Jvdz0wOwogICAgICAgIH0KICAgICAgICBwZXJfcm93Kys7CiAgICAgICAgaWYoc3RhcnQ+PW4pYnJlYWs7CiAgICB9CiAgICAKICAgICBmb3IgKGludCBpID0gMDsgaSA8IG47IGkrKykgewogICAgICAgIGZvciAoaW50IGogPSAwOyBqIDwgbjsgaisrKSB7CiAgICAgICAgICAgIGlmIChtYXRyaXhbaV1bal0gPT0gMCkKICAgICAgICAgICAgICAgIHN0ZDo6Y291dCA8PCBzdGQ6OnNldHcoMykgPDwgIiAiIDw8ICJcdCI7IAogICAgICAgICAgICBlbHNlCiAgICAgICAgICAgICAgICBzdGQ6OmNvdXQgPDwgc3RkOjpzZXR3KDMpIDw8IG1hdHJpeFtpXVtqXSA8PCAiXHQiOyAKICAgICAgICB9CiAgICAgICAgc3RkOjpjb3V0IDw8IHN0ZDo6ZW5kbDsKICAgIH0KCiAgICByZXR1cm4gMDsKfQ==