天天看點

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的用法詳解

繼續閱讀