LeetCode面試題29.順時針打印矩陣 每日一題6月5日

問題描述:

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

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof

示例 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]

解題思路:

簡單題,注意邊界就行。

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if(matrix.empty()) return res;
        int n = matrix.size();
        int m = matrix[0].size();
        int left=0,right=m-1,top=0,bot=n-1;
        while(left<=right && top<=bot){
            for(int i=left;i<=right;i++){
                res.push_back(matrix[top][i]);
            }
            for(int i=top+1;i<=bot;i++){
                res.push_back(matrix[i][right]);
            }
            if(top!=bot){
                for(int i=right-1;i>=left;i--){
                    res.push_back(matrix[bot][i]);
                }
            }
            if(left!=right){
                for(int i=bot-1;i>top;i--){
                    res.push_back(matrix[i][left]);
                }
            }
            left++,right--,top++,bot--;
        }
        return res;
    }   
};

 

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