leetcode Spiral Matrix II

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   使用   for   sp   

題目:是Spiral Matrix相關的的。這題的意思是給定一個n,那麼在n*n的矩陣裡按照迴圈記錄將1,2,3,..., n*n。如下如果給定3,那麼:

[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
一開始我想是不是有數學公式直接下標對應的,那直接遍曆輸出就可以了。但是推了一會,沒有什麼好的頭緒。於是就分情況討論了,和Spiral Matrix一樣的分情況,只是這裡的分情況是記錄在數組裡面。
利用上,下,左,右,分別記錄每次迴圈可以到達的四個邊界,我們每次就輸出一環,走完一環往內走。
需要注意的:
1.要用下標訪問vector<vector> >需要先聲明大小才可以使用下標訪問。
2.每走完一環,相應更新四個方向。
3.如果是奇數,那麼n*n這個數需要另外存。也就是存在[n/2][n/2]的位置。
class Solution {public:vector<vector<int> > generateMatrix(int n){    vector<int> sub(n);    vector<vector<int> > ans(n, sub); // 也可以用vector<vector<int> > ans(n, vector<int>(n));    if (n < 1) return ans;    int val = 1, left = 0, right = n-1, up = 1, down = n-1;    for (int i = 0; i < n/2; i++)    {        for (int j = left; j <= right; j++)        {            ans[i][j] = val++;        }        for (int j = up; j <= down; j++)        {            ans[j][right] = val++;        }        for (int j = right - 1; j>=left; j--)        {            ans[down][j] = val++;        }        for (int j = down - 1; j >= up; j--)        {            ans[j][left] = val++;        }        left++; right--; up++; down--;    }    if (n%2)        ans[n/2][n/2] = n*n;    return ans;}};

 

leetcode Spiral Matrix II

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.