-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnti Diagonal Traversal of Matrix
122 lines (110 loc) Β· 3.26 KB
/
Anti Diagonal Traversal of Matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include<bits/stdc++.h>
#define int long long
using namespace std;
int32_t main() {
int tt = 1;
cin >> tt;
while (tt--) {
int n;
cin >> n;
if (n == 2) {
cout << -1 << endl;
continue;
}
vector<int> v1, v2;
for (int i = 1; i <= n * n; i++) {
if (i % 2)
v1.push_back(i);
else
v2.push_back(i);
}
vector<vector<int>> v(n, vector<int>(n, -1));
vector<vector<int>> ans(n, vector<int>(n, 0));
if (n % 2 == 0) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1; j++) {
if (i == j)
v[i][j] = 1;
else if (v[i][j] == -1) {
if (i > j) {
v[i][j] = 0;
v[j][i] = 1;
} else {
v[i][j] = 1;
v[j][i] = 0;
}
}
}
}
v[n - 1][n - 1] = 1;
int c = (n - 2) / 2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (v[i][j] != -1)
continue;
if (i == n - 1 || j == n - 1) {
if (c) {
v[i][j] = 1;
v[j][i] = 0;
c--;
} else {
v[i][j] = 0;
v[j][i] = 0;
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (v[i][j] == 0) {
ans[i][j] = v2.back();
v2.pop_back();
} else {
ans[i][j] = v1.back();
v1.pop_back();
}
}
}
if (((n - 2) / 2) % 2 == 0) {
swap(ans[n - 2][0], ans[n - 2][n - 2]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
continue;
}
v[0][0] = 1;
int cnt = 1;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (cnt == (n * n + 1) / 2)
break;
v[i][j] = 1;
v[j][i] = 1;
cnt += 2;
}
if (cnt == (n + 1) / 2)
break;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (v[i][j] == -1) {
ans[i][j] = v2.back();
v2.pop_back();
} else {
ans[i][j] = v1.back();
v1.pop_back();
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
}
}