蛇形矩阵 C++

蛇形矩阵

https://ac.nowcoder.com/acm/problem/22231

#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>

using namespace std;

int a[1005][1005];

int main(){
    int n, cnt = 1;
    cin >> n;
    for(int i = 1; i <= n; ++i){
        if(i % 2 == 0){
            for(int j = i; j >= 1; --j) a[i + 1 - j][j] = cnt++;
        }else{
            for(int j = 1; j <= i; ++j) a[i + 1 - j][j] = cnt++;
        }
    }
    for(int i = n + 1; i <= 2 * n - 1; ++i){
        if(i % 2 == 0){
            for(int j = n; j >= i - n + 1; --j) a[i + 1 - j][j] = cnt++;
        }else{
            for(int j = i - n + 1; j <= n; ++j) a[i + 1 - j][j] = cnt++;
        }
    }
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= n; ++j){
            cout << a[i][j] << ' ';
        }
        cout << endl;
    }
    return 0;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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