2020-06-05 LeetCode 面試題29 順時針打印矩陣 C++

題目:面試題29. 順時針打印矩陣

 輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字。

示例1:

輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]

示例2:

輸入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
輸出:[1,2,3,4,8,12,11,10,9,5,6,7]

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

 注意:本題與主站 54 題相同:https://leetcode-cn.com/problems/spiral-matrix/

 思路:題目本身挺簡單的,按照順時針規律從裏到外遍歷就好了,問題就是對邊界情況的處理比較麻煩,需要注意的有空矩陣、行向量、列向量等,自己寫了個難看的就不貼了,想了半天也不知道怎麼把特殊情況一般化。下面是官方題解,但是感覺也不夠簡潔,還是對行向量和列向量的情況進行了單獨判斷

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        //空矩陣
        if (matrix.empty()) 
            return {};
        //行列大小
        int rows = matrix.size(), columns = matrix[0].size();
        vector<int> ans;
        //上下左右的邊界
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
        	//從左上往右上
            for (int j = left; j <= right; j++)
                ans.push_back(matrix[top][j]);
            //從右上往右下
            for (int i = top + 1; i <= bottom; i++) 
                ans.push_back(matrix[i][right]);
            //針對行向量和列向量的處理
            if (left < right && top < bottom) {
                //從右下往左下
                for (int j = right - 1; j > left; j--) 
                    ans.push_back(matrix[bottom][j]);
                //從左下往左上
                for (int i = bottom; i > top; i--) 
                    ans.push_back(matrix[i][left]);
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return ans;
    }
};

運行結果:
在這裏插入圖片描述
 還是碼一下,以後複習的時候希望能找到簡潔的實現。

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