leetcode#54 spiral matrix

來源:互聯網
上載者:User

標籤:matrix   起點   back   輸入   順序   push   樣本   class   bsp   

給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

樣本 1:

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

樣本 2:

輸入:[  [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:    /*    1234    5678    9876    5432        */    vector<int> spiralOrder(vector<vector<int>>& matrix) {        //似乎沒有規律,對於一個矩陣,記錄它的起點,0,0,構成一個m*n,先輸出第一行,再輸出最後一列的n-2個,再輸出最後一行,再輸出第一列的n-2個        //然後修改起點為1,1,m,n為m-2,n-2        if(matrix.size()==0) return {};        vector<int> result;        spiralOrder(matrix,result,0,0,matrix.size(),matrix[0].size());        return result;    }        void spiralOrder(vector<vector<int>>& matrix,vector<int>& result,int x,int y,int m,int n)     {        if (m<=0 || n<=0) return;        if (m == 1 || n == 1)        {            for (int i = 0; i != m; ++i)                for (int j = 0; j != n; ++j)                    result.push_back(matrix[x + i][y + j]);            return;        }        for (int i = 0; i<n; ++i)            result.push_back(matrix[x + 0][y + i]);        for (int i = 1; i<m - 1; ++i)            result.push_back(matrix[x + i][y + n - 1]);        for (int i = n - 1; i >= 0; --i)            result.push_back(matrix[x + m - 1][y + i]);        for (int i = m - 2; i > 0; --i)            result.push_back(matrix[x + i][y + 0]);        m -= 2;        n -= 2;        spiralOrder(matrix, result, x + 1, y + 1, m, n);    }            };       

 

leetcode#54 spiral matrix

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.