题解 | 回型矩阵

回型矩阵

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

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, num;
    cin >> n;
    num = 1;
    int a[n][n];
  //top记录下一个填写的左上行,right为下一个填写的右上列,left威威下一个填写的右下行,bottom为下一个填写的坐下列
    int top = 0, right = n - 1, bottom = 0, left =  n - 1;
    while (num <= n * n) {
        for (int i = top; i <= right; i++) {
            a[top][i] = num;
            num++;
        }
        top++;
        for (int i = top; i <= left; i++) {
            a[i][right] = num;
            num++;
        }
        right--;
        for (int i = right; i >= bottom; i--) {
            a[left][i] = num;
            num++;
        }
        left--;
        for (int i = left; i >= top; i--) {
            a[i][bottom] = num;
            num++;
        }
        bottom++;
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout << a[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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