【leetcode】劍指 Offer 29. 順時針打印矩陣(shun-shi-zhen-da-yin-ju-zhen-lcof)(模擬)[簡單]

鏈接

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

耗時

解題:38 min
題解:10 min

題意

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

思路

將矩陣的每一圈作爲一個循環節,問題即變爲按從外到內的順序順時針輸出矩陣每一圈的數字。一圈順時針讀取又可拆分爲 4 部分,以最左上角的數字爲起點,從左到右,從上到下,從右到左,從下到上。

PS: 特殊情況有一圈只有一行或一列,矩陣爲空。

AC代碼

class Solution {
public:
    void solve(int x, int y, int xs, int xt, int ys, int yt, vector<vector<int>>& matrix, vector<int> &ans) {
        ans.push_back(matrix[x][y]);
        while(++y < yt) {
            ans.push_back(matrix[x][y]);
        }
        if(xt-xs == 1) return ;
        y = yt-1;
        while(++x < xt) {
            ans.push_back(matrix[x][y]);
        }
        if(yt-ys == 1) return ;
        x = xt-1;
        while(--y >= ys) {
            ans.push_back(matrix[x][y]);
        }
        y = ys;
        while(--x > xs) {
            ans.push_back(matrix[x][y]);
        }
    }
    
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if(matrix.empty()) return {};
        vector<int> ans;
        int n = matrix.size();
        int m = matrix[0].size();
        for(int i = 0, j = 0; i < (n+1)/2 && j < (m+1)/2; ++i, ++j) {
            solve(i, j, i, n-i, j, m-j, matrix, ans);
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章