-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiral_matrix.cpp
More file actions
76 lines (61 loc) · 1.38 KB
/
spiral_matrix.cpp
File metadata and controls
76 lines (61 loc) · 1.38 KB
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
#include <iostream>
int **generateSpiralMatrix(int n) {
int **matrix = new int *[n];
for (int i = 0; i < n; i++) {
matrix[i] = new int[n];
}
int top{0};
int bottom{n};
int left{0};
int right{n};
int value{1};
while ((left < right) && (top < bottom)) {
// Top row
for (int i = left; i < right; i++) {
matrix[top][i] = value++;
}
top += 1;
// Right column
for (int i = top; i < bottom; i++) {
matrix[i][right - 1] = value++;
}
right -= 1;
if (!(left < right) || !(top < bottom)) {
break;
}
// Bottom row
for (int i = right - 1; i >= left; i--) {
matrix[bottom - 1][i] = value++;
}
bottom -= 1;
// Left column
for (int i = bottom - 1; i >= top; i--) {
matrix[i][left] = value++;
}
left += 1;
}
return matrix;
}
const void printMatrix(int **matrix, int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << matrix[i][j];
}
std::cout << '\n';
}
}
int main(int argc, char *argv[]) {
int n{};
do {
std::cout << "Матрицын N (NxN) oруулна уу: ";
std::cin >> n;
} while (n < 0 || n > 1000000);
int **matrix{generateSpiralMatrix(n)};
std::cout << "X, Y оруулна уу: ";
int x{};
int y{};
std::cin >> x >> y;
std::cout << matrix[x][y] << '\n';
// printMatrix(matrix, n);
return 0;
}