注册 登录
编程论坛 C语言论坛

螺旋矩阵怎么实现

swiflovestor 发布于 2022-10-27 11:04, 873 次点击
只有本站会员才能查看附件,请 登录

螺旋矩阵,不用数组可以实现么,只用循环。
3 回复
#2
rjsp2022-10-27 11:09
举个样例输入为偶数的样例输出来看看,比如 4*4的螺旋矩阵是什么样子?
#3
swiflovestor2022-10-27 15:29
回复 2楼 rjsp
16 15 14 13
 5  4  3 12
 6  1  2 11
 7  8  9 10
只有本站会员才能查看附件,请 登录

也是一样顺时针旋转
#4
rjsp2022-10-28 13:16
第一,如果是规则是 第一行从左到右 开始排布,那任何矩阵都可以排布,为什么题目要限定为“N*N的方阵”,这不是误导人嘛!

第二,你贴的是图片,而不是文字,从图片中我没法看出 空格有多少个。而且你最后的贴图与最开始的题图,空格数明显不一致。

我随手写了一个,未必正确,但思路是可行的
程序代码:
#include <stdio.h>

void foo( unsigned row, unsigned col, int output_width )
{
    for( unsigned i=0; i!=row*col; ++i )
    {
        const unsigned r = i/col; // 第r行
        const unsigned c = i%col; // 第c列

        
// 与 上、右、下、左 四边的距离
        const unsigned ths = r - 0;
        const unsigned rhs = col-1 - c;
        const unsigned lhs = c - 0;
        const unsigned bhs = row-1 - r;

        if( ths<=rhs && ths<=lhs && ths<=bhs ) // 处于 第ths圈的上边
            printf( "%*u%c", output_width, row*col - ((row*col-(row-2*ths)*(col-2*ths)) + (0*col+0*row-0*rhs-0) + (lhs-ths)), " \n"[c+1==col] );
        else if( rhs<ths && rhs<=bhs && rhs<=lhs ) // 处于 第rhs圈的右边
            printf( "%*u%c", output_width, row*col - ((row*col-(row-2*rhs)*(col-2*rhs)) + (1*col+0*row-2*rhs-1) + (ths-rhs)), " \n"[c+1==col] );
        else if( bhs<ths && bhs<rhs && bhs<=lhs ) // 处于 第bhs圈的下边
            printf( "%*u%c", output_width, row*col - ((row*col-(row-2*bhs)*(col-2*bhs)) + (1*col+1*row-4*bhs-2) + (rhs-bhs)), " \n"[c+1==col] );
        else if( lhs<ths && lhs<rhs && lhs<bhs ) // 处于 第lhs圈的左边
            printf( "%*u%c", output_width, row*col - ((row*col-(row-2*lhs)*(col-2*lhs)) + (2*col+1*row-6*lhs-3) + (bhs-lhs)), " \n"[c+1==col] );
    }
}

int main( void )
{
    unsigned n;
    scanf( "%u", &n );
    foo( n, n, 3 );
}
1