C++程序 在矩阵中形成线圈
给定一个正整数n,代表一个由左至右、由上至下填充1到n值的4n x 4n矩阵的维度。从矩阵中形成两个线圈并打印它们。
例子:
输入: n = 1;
输出:线圈1:10 6 2 3 4 8 12 16
线圈2:7 11 15 14 13 9 5 1
解释:矩阵如下
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
输入: n = 2;
输出:线圈1:36 28 20 21 22 30 38 46 54
53 52 51 50 42 34 26 18 10
2 3 4 5 6 7 8 16 24 32 40
48 56 64
线圈2:29 37 45 44 43 35 27 19 11 12
13 14 15 23 31 39 47 55 63 62
61 60 59 58 57 49 41 33 25 17
9 1
矩阵中的总元素为16n 2 。所有元素被分为两个线圈。每个线圈都有8n 2 个元素。我们做两个这样大小的数组。我们首先按给定顺序遍历线圈1中的元素来填充它们。一旦我们填充了线圈1中的元素,我们可以使用公式coil2[i] = 16*n*n + 1 -coil1[i]
来获取其他线圈2的元素。
// C++ program to print 2 coils of a
// 4n x 4n matrix.
#include<iostream>
using namespace std;
// Print coils in a matrix of size 4n x 4n
void printCoils(int n)
{
// Number of elements in each coil
int m = 8*n*n;
// Let us fill elements in coil 1.
int coil1[m];
// First element of coil1
// 4*n*2*n + 2*n;
coil1[0] = 8*n*n + 2*n;
int curr = coil1[0];
int nflg = 1, step = 2;
// Fill remaining m-1 elements in coil1[]
int index = 1;
while (index < m)
{
// Fill elements of current step from
// down to up
for (int i=0; i<step; i++)
{
// Next element from current element
curr = coil1[index++] = (curr - 4*n*nflg);
if (index >= m)
break;
}
if (index >= m)
break;
// Fill elements of current step from
// up to down.
for (int i=0; i<step; i++)
{
curr = coil1[index++] = curr + nflg;
if (index >= m)
break;
}
nflg = nflg*(-1);
step += 2;
}
/* get coil2 from coil1 */
int coil2[m];
for (int i=0; i<8*n*n; i++)
coil2[i] = 16*n*n + 1 -coil1[i];
// Print both coils
cout << "Coil 1 : ";
for(int i=0; i<8*n*n; i++)
cout << coil1[i] << " ";
cout << "
Coil 2 : ";
for (int i=0; i<8*n*n; i++)
cout << coil2[i] << " ";
}
// Driver code
int main()
{
int n = 1;
printCoils(n);
return 0;
}
输出:
线圈1:10 6 2 3 4 8 12 16
线圈2:7 11 15 14 13 9 5 1
时间复杂度: O(n 2 ),其中n表示给定的整数。
辅助空间: O(n 2 ),其中n表示给定的整数。