题解 | #蛇形矩阵#

蛇形矩阵

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

alt

每个颜色的折线表示一次大循环。 看图可知,这样难免会发生越界的情况, 所以给数组元素赋值时加个判断条件, 当行号和列号都不超过n时赋值,超过n时则不赋。 row为行号, col为列号, count为计数器,是每次给元素赋的值。

int main()
{
    int n;
    scanf("%d", &n);
    int count = 1;
    int row = 0;
    int col = 0;
    int arr[1000][1000] = {0};
    while(count <= n*n)
    {
        for(int i=0; i<2; i++)
        {
            if(row<n && col<n)
                arr[row][col] = count++;
            col++;
        }
        col--;
        while(col)
        {
            row++;
            col--;
            if(row<n && col<n)
                arr[row][col] = count++;
        }
        row++;
        while(row)
        {
            if(row<n && col<n)
                arr[row][col] = count++;
            row--;
            col++;
        }  
    }
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
            printf("%d ", arr[i][j]);
        printf("\n");
    }
    return 0;
}
全部评论
牛客网可以通过,但在其他编译器中由于越界访问会报错
点赞 回复 分享
发布于 2024-03-06 13:54 湖南

相关推荐

05-12 17:28
已编辑
门头沟学院 硬件开发
ldf李鑫:不说公司名祝你以后天天遇到这样的公司
点赞 评论 收藏
分享
评论
13
收藏
分享

创作者周榜

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