题解 | 回型矩阵

回型矩阵

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

#include <stdio.h>

int main() {
    int n;
    scanf("%d",&n);
    int arr[19][19] = {0};
    int left = 0;
    int right = n - 1;
    int top = 0;
    int bottom  = n -1 ;
    int num = 1;
    while(top <= bottom&&left <= right)
    {
        //从左到右
        for(int i = left ; i <= right ; i++)
        {
            arr[top][i] = num++;
        }
        top++;
       // 从上到下
       if(left <= right)
       {
        for(int j = top; j<=bottom;j++)
       {
        arr[j][right] = num++;
       }
       right--;
       }
       
       //从右到左
       if(left<=right)
       {
        for(int g = right;g >= left; g--)
       {
        arr[bottom][g] = num++;
       }
       bottom--;
       }
       //从下到上
      if(top <= bottom)
      {
         for(int l = bottom; l >=top;l--)
       {
        arr[l][left] = num++;
       }
       left++;
    }
      }
    for(int i = 0 ; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}

主要还是设置边界,然后就是注意每次边界改变后要进行一个判断,防止越界

全部评论

相关推荐

牛客245670684号:虚拟货币预测正确率百分之99,还要找工作干嘛,不早就财富自由了
点赞 评论 收藏
分享
03-03 10:35
3d人士会梦见住进比弗利山庄吗:这四个项目属于是初学者的玩具了。不知道面试官咋问,而且双非本搞算法除了9,还是保守至少c9
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-26 16:16
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务