劍指offer之面試題20:順時針打印矩陣

題目:

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

思路:

用左上和右下的座標定位出一次要旋轉打印的數據,一次旋轉打印結束後,往對角分別前進和後退一個單位。需要加入條件判斷,防止出現單行或者單列的情況。

代碼:

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) 
    {
		int columns=matrix[0].size();
        int rows=matrix.size();
        vector<int> res;
        if(columns<=0||rows<=0)
        {
            return res;
        }
        //起始點
           // 定義四個關鍵變量,表示左上和右下的打印範圍
        int left = 0, top = 0, right = columns - 1, bottom = rows - 1;
        while (left <= right && top <= bottom)
        {
            // left to right
            for (int i = left; i <= right; ++i)  res.push_back(matrix[top][i]);
            // top to bottom
            for (int i = top + 1; i <= bottom; ++i)  res.push_back(matrix[i][right]);
            // right to left
            if (top != bottom)
            for (int i = right - 1; i >= left; --i)  res.push_back(matrix[bottom][i]);
            // bottom to top
            if (left != right)
            for (int i = bottom - 1; i > top; --i)  res.push_back(matrix[i][left]);
            left++,top++,right--,bottom--;
        }
        return res;
    
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章