题解 | #蛇形矩阵# 基于vector容器

蛇形矩阵

https://www.nowcoder.com/practice/649b210ef44446e3b1cd1be6fa4cab5e

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

int main() {
    int n;
    cin >> n;
    vector<vector<int>> arr(n,vector<int>(n,0));
    int tmp = n,val = 1;
    int i=0,j=0;
    int num = 0;
    while(i >= 0){
        arr[i][j] = val++;
        if(i > 0){
            i -= 1;
            j += 1;
        }else if(i == 0){
            if(j == n-1){
                break;
            }
            i = j + 1;
            j = 0;
        }
    }

    tmp = n;
    i = 0;
    while(tmp > 0){
        for(int k=0; k<tmp;k++){
            cout << arr[i][k] << " ";
        }
        cout << endl;
        i++;
        tmp--;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

本题难点在于矩阵的构造,本思路采用的是在值递增的基础上更新位置的方式来构造矩阵。

全部评论

相关推荐

11-19 18:44
已编辑
成都理工大学 Java
程序员花海:我面试过100+校招生,大厂后端面试不看ACM,竞赛经历含金量低于你有几份大厂实习 这个简历整体来看不错 可以海投
如何写一份好简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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