题解 | #蛇形矩阵#

蛇形矩阵

https://www.nowcoder.com/practice/f228a074c5274619b26be544962375e1

#include <stdio.h>
 
int main()
{
    int n, i, j, step = 2, sum = 1, arr[1000][1000] = { 0 };
    scanf("%d", &n);
    arr[0][0] = 1;
    while (sum < n)
    {
        if (sum % 2)
        {
            for (i = 0; i <= sum; i++)
            {
                arr[i][sum-i] = step;
                step++;
            }
        }
        else
        {
            for (i = sum; i >= 0; i--)
            {
                arr[i][sum-i] = step;
                step++;
            }
        }
        sum++;
    }
    while (sum <= 2 * (n - 1))
    {
        if (sum % 2)
        {
            for (i = sum-n+1; i <= n-1; i++)
            {
                arr[i][sum-i] = step;
                step++;
            }
        }
        else
        {
            for (i = n - 1; i >= sum - n + 1; i--)
            {
                arr[i][sum-i] = step;
                step++;
            }
        }
        sum++;
    }
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
        return 0;
}

全部评论

相关推荐

巧克力1:双选会不如教室宣讲会
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务