题解 | 回型矩阵

回型矩阵

https://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343

#include <stdio.h>
#define N 20
int main()
{
    int n;
    scanf("%d",&n);

    int arr[N][N] = {0};
    int i,j;

    int top = 0;
    int left = 0;
    int right = n-1;
    int bottom = n-1;
    int count = 0;

    while(count < n*n)
    {
        for(j = left; j <= right&&count < n*n; j++)
        {
            count++;
            arr[top][j] = count;
        }
        top++;

        for(i = top; i <= bottom&&count < n*n; i++)
        {
            count++;
            arr[i][right] = count;
        }
        right--;

        if(top <= bottom)
        {
            for(j = right; j >= left&&count < n*n; j--)
            {
                count++;
                arr[bottom][j] = count;
            }
            bottom--;
        }
        
        if(left <= right)
        {
            for(i = bottom; i >= top&&count < n*n;i--)
            {
                count++;
                arr[i][left] = count;
            }
            left++;
        }
        
    }

    for(i = 0; i < n; i++)
    {
        for(j = 0; j < n; j++)
        {
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}

全部评论

相关推荐

牛至超人:您好,京东物流岗了解一下吗?负责精加工食品的端到端传输
点赞 评论 收藏
分享
2025-11-26 09:37
山西大学 测试工程师
累死的一条狗:学长你电脑闹鬼了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务