天天看点

C++实现转圈打印矩阵

给定一个整型矩阵 matrix,请按照转圈的方式打印它。

1. 题目描述

例如:

   1  2  3  4

   5  6  7  8

   9   10   11  12

   13  14  15  16

打印结果为:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10

要求额外空间复杂度为O(1).

2. 思路分析

先打印最外圈,然后打印里面的一圈.只要设计出打印出打印正方形的四条边就行了,同时注意边界条件,即如果只有一行或者一列的条件.
C++实现转圈打印矩阵

3. 代码

#include <iostream>
#include <vector>

template<typename T>
void pirntEdage(std::vector<std::vector<T>>& my_matrix, int tR, int tC, int dR, int dC) {
    if (tR == dR) { // same rows
        for (int i = tC; i <= dC; ++i) {
            std::cout << my_matrix[tR][i] << ",";
        }
    } else if (tC == dC) {  // same colums
        for (int i = tR; i <= dR; ++i) {
            std::cout << my_matrix[i][tC] << ",";
        }
    } else {    // print 4 edges
        int curR = tR;
        int curC = tC;
        while (curC != dC) {
            std::cout << my_matrix[tR][curC] << ",";
            ++curC;
        }
        while (curR != dR) {
            std::cout << my_matrix[curR][dC] << ",";
            ++curR;
        }
        while (curC != tC) {
            std::cout << my_matrix[dR][curC] << ",";
            --curC;
        }
        while (curR != tR) {
            std::cout << my_matrix[curR][tC] << ",";
            --curR;
        }
    }
}

template<typename T>
void spiralOrderPrint(std::vector<std::vector<T>>& my_matrix) {
    int tR = 0;
    int tC = 0;
    int dR = my_matrix.size() - 1;
    int dC = my_matrix[0].size() - 1;
    while (tR <= dR && tC <= dC) {
        pirntEdage(my_matrix, tR++, tC++, dR--, dC--);
    }
}
int main()
{
    std::vector<std::vector<int>> my_matrix = {{1, 2, 3, 4},
                                              {5, 6, 7, 8},
                                              {9, 10, 11, 12},
                                              {13,14, 15, 16}};
    spiralOrderPrint(my_matrix);
    return 0;
}

           
C++实现转圈打印矩阵

4. 参考文献

  1. 顺时针打印矩阵——C++
  2. 【已解决】Linux下出现Segmentation Fault(core dump)错误
  3. 使用vector创建一个二维数组(一)
  4. c++中vector的用法详解

继续阅读