螺旋矩阵是一个像螺旋一样工作的矩阵,它将开始从圆的原点开始,按顺时针方向旋转。因此,任务是使用从 2 → 4 → 6 → 8 → 10 → 12 → 14 → 1 6→ 18 开始的 o(1) 空间以螺旋形式打印矩阵。
下面是示例螺旋矩阵 -
示例input: 3output: 9 8 7 2 1 6 3 4 1
解决具有无限空间的代码变得很容易,但这并不像最佳程序那样有效,或者代码在内存和时间上都是有效的。因此,为了保持螺旋顺序,使用了四个循环,每个循环用于矩阵的上、右、下和左角,但是如果我们将矩阵分为两部分,即右上角和左下角,我们可以直接使用这个概念
对于右上半部分,
mat[i][j] = (n-2*x)*(n-2*x)-(i-x)-(j-x)
对于左下半部分,
mat[i][j] = (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)
注意-我们正在编写用于打印 2 的矩阵倍数的程序
算法int spiralmatrix(int n)startstep 1: declare i, j, a, b, xstep 2: loop for i = 0 and i < n and i++ loop for j = 0 and j < n and j++ find the minimum in (i<j ) and assign it to a find the minimum (n-1-i) < (n-1-j) and assign it to b then assign the least value from a and b to x if i <= j then, print the value of 2* ((n-2*x)*(n-2*x) - (i-x) - (j-x)) else print the value of 2*((n-2*x-2)*(n-2*x2) + (i-x) + (j-x)) end loop print newlineend loopstop
示例#include <stdio.h>//for n x n spiral matrixint spiralmatrix(int n){ int i, j, a, b, x; // x stores the layer in which (i, j)th element exist for ( i = 0; i < n; i++){ for ( j = 0; j < n; j++){ // finds minimum of four inputs a = ((i<j ? i : j)); b = ((n-1-i) < (n-1-j) ? (n-1-i) : (n-1-j)); x = a < b ? a : b; // for upper right half if (i <= j) printf("%d\t ", 2 * ((n-2*x)*(n-2*x) - (i-x) - (j-x))); // for lower left half else printf("%d\t ", 2*((n-2*x-2)*(n-2*x-2) + (i-x) + (j-x))); } printf("
"); }}int main(int argc, char const *argv[]){ int n = 3; spiralmatrix(n); return 0;}
输出如果我们运行上面的程序,那么它将生成以下输出 -
18 16 144 2 126 8 10
以上就是使用c程序打印n x n的螺旋矩阵,使用o(1)额外空间的详细内容。
