螺旋打印矩阵

思想

使用四个指针LR,LC,RR,RC
(LR,LC)表示左上角位置坐标
(RR,RC)表示右下角位置坐标
将整个螺旋打印过程由外向内逐层打印

打印函数output()

void output(int **arr, int LR, int LC, int RR, int RC){
    if(LR == RR){
        for(int i = LC; i <= RC; i++){
            cout << arr[LR][i] << " ";
        }
        cout << endl;
    }else if(LC == RC){
        for(int i = LR; i <= RR; i++){
            cout << arr[i][LC] << " ";
        }
        cout << endl;
    }else{
        int curR = LR;
        int curC = LC;
        while(curC < RC){
            cout << arr[curR][curC++] << " ";
        }
        while(curR < RR){
            cout << arr[curR++][curC] << " ";
        }
        while(curC > LC){
            cout << arr[curR][curC--] << " ";
        }
        while(curR > LR){
            cout << arr[curR--][curC] << " ";
        }
    }
}

相关阅读

旋转正方形矩阵
螺旋打印矩阵
Z字打印矩阵
行列排序矩阵找数

完整代码

#include <bits/stdc++.h>
using namespace std;

int **inputArr(int n, int m){
    int **arr;
    arr = new int* [n];
    for(int i = 0; i < n; i++){
        arr[i] = new int [m];
    }
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cin >> arr[i][j];
        }
    }
    return arr;
}

void outputArr(int **arr, int n, int m){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}

void output(int **arr, int LR, int LC, int RR, int RC){
    if(LR == RR){
        for(int i = LC; i <= RC; i++){
            cout << arr[LR][i] << " ";
        }
        cout << endl;
    }else if(LC == RC){
        for(int i = LR; i <= RR; i++){
            cout << arr[i][LC] << " ";
        }
        cout << endl;
    }else{
        int curR = LR;
        int curC = LC;
        while(curC < RC){
            cout << arr[curR][curC++] << " ";
        }
        while(curR < RR){
            cout << arr[curR++][curC] << " ";
        }
        while(curC > LC){
            cout << arr[curR][curC--] << " ";
        }
        while(curR > LR){
            cout << arr[curR--][curC] << " ";
        }
    }
}

int main(){
    int **arr;
    int n, m;
    cin >> n >> m;
    int LR = 0, LC = 0;
    int RR = n-1, RC = m-1;
    arr = inputArr(n, m);
    while(LR <= RR && LC <= RC){
        output(arr,LR++,LC++,RR--,RC--);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值