劍指offer之順時針打印矩陣

1.題目描述

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣: 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.

2.問題分析

因爲是順時針打印,所以每次我們打印矩陣最外圍一圈,之後矩陣縮小一圈,重複上述過程,打印完畢。打印一圈的時候,需要分成4步:

  1. 頂行從左列到右列的值;
  2. 最右列從頂行 + 1到底行的值;
  3. 底行從右列 - 1到左列的值(底行需要大於頂行);
  4. 最左列從底行 - 1到頂行 + 1的值(左列需要大於右列)。

3.源代碼

vector<int> printMatrix(vector<vector<int> > matrix) {
    vector<int> res;
    //行數
    int rows = matrix.size();
    if(rows == 0)
        return res;
    //列數    
    int cols = matrix[0].size();
    if(cols == 0)
        return res;
    //定義一個矩陣的左,右,頂,底的值
    int left = 0, top = 0, right = cols - 1, bottom = rows - 1;
    while(left <= right && top <= bottom)
    {
        //top行從left到right的值保存到res
        for(int x = left; x <= right; ++x)
            res.push_back(matrix[top][x]);
        //right列從top+1到bottom的值保存到res,
        for(int y = top + 1; y <= bottom;++y)
            res.push_back(matrix[y][right]);
        //先判斷該矩陣是否有兩行
        if(bottom > top)
        {
            for(int x = right - 1;x >= left; --x)
                res.push_back(matrix[bottom][x]);
        }
        if(right > left)
        {
            for(int y = bottom - 1; y > top; --y)
                res.push_back(matrix[y][left]);
        }

        ++left;
        ++top;
        --right;
        --bottom;
    }
    return res;
}
發佈了84 篇原創文章 · 獲贊 55 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章