题解 | 顺时针打印数字矩阵

顺时针打印数字矩阵

https://www.nowcoder.com/practice/ce0c22a435114108bd9acc75f81b5802

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

void roundout(int m, int n, vector<vector<int>> mn){
    int left,right,top,bottom;
    left = 0;
    right = n-1;
    top = 0;
    bottom = m-1;
    
    int i,j;
    int num = 0;
    while(true){
        if(left>right) break;
        for(i=top,j=left;j<=right;j++) cout<<(num++==0?"":",")<<mn[i][j];
        top +=1;

        if(top>bottom) break;
        for(i=top,j=right;i<=bottom;i++) cout<<(num++==0?"":",")<<mn[i][j];
        right -=1;

        if(left>right) break;
        for(i=bottom,j=right;j>=left;j--) cout<<(num++==0?"":",")<<mn[i][j];
        bottom -=1;

        if(top>bottom) break;
        for(i=bottom,j=left;i>=top;i--) cout<<(num++==0?"":",")<<mn[i][j];
        left +=1;
    }
    cout<<endl;
}

int main() {
    int m, n;
    
    while(cin >> m >> n && m!=-1 && n!=-1){
        vector<vector<int>> mn(m,vector<int>(n,0));

        for(int i=0;i<m;i++){
            for (int j=0; j<n; j++) {
                int value;
                cin >> mn[i][j];
            }
        }
        
        roundout(m,n,mn);
    }
    
    
    
}
// 64 位输出请用 printf("%lld")

拆分问题,每个while循环负责打印一圈,一圈则分别是上,右,下,左边,每遍历一条边,更新遍历边界,任何一条边遍历前要检查边界合法性,这是退出条件;最后注意处理一下打印的逗号分隔

全部评论

相关推荐

我是没经验的毕业生,这啥情况啊会不会是hr在刷kpi
JamesGosli...:字节boss属于是群发了,我都快入职字节了,其他部门还在和我boss打招呼
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
06-12 17:46
门头沟学院 Java
运营你豪哥:来说重点: ​1.项目前置,时间倒序。​​ 2.​项目描述强化结果与量化效果(STAR原则里的R)。​​ ​3.个人技能精炼,明确掌握程度,突出核心。​​ ​4.增加强有力开头的个人总结部分。​​ 5.​优化教育背景(成绩排名)、合并奖项与活动。​​
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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