LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj

題目連結:Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

For example,

Given n = 3,

You should return the following matrix:

[  [ 1, 2, 3 ],  [ 8, 9, 4 ],  [ 7, 6, 5 ] ] 

這道題的要求是返回長寬均為n的矩陣,其元素是按照1~n^2的螺旋順序排列。

和Spiral Matrix同樣簡單的數組操作問題,只需要按右、下、左、上的順序逐行或列遍曆數組。不過在處理邊界問題上,這題貌似更容易一些:可以先初始化二維數組均為0,然後填寫的時候碰到非0值的時候就改變方向即可。

時間複雜度:O(n2)

空間複雜度:O(n2)

 1 class Solution  2 { 3 public: 4     vector<vector<int> > generateMatrix(int n) 5     { 6         vector<vector<int> > vvi(n, vector<int>(n, 0)); 7          8         if(n < 1) 9             return vvi;10         11         int i = 0, j = 0, k = 1;12         vvi[i][j] = k;13         while(k < n * n)14         {15             while(j + 1 < n && vvi[i][j + 1]==0)16                 vvi[i][++ j] = ++ k;17             18             while(i + 1 < n && vvi[i + 1][j]==0)19                 vvi[++ i][j] = ++ k;20             21             while(j - 1 >= 0 && vvi[i][j - 1]==0)22                 vvi[i][-- j] = ++ k;23             24             while(i - 1 >= 0 && vvi[i - 1][j]==0)25                 vvi[-- i][j] = ++ k;26         }27         28         return vvi;29     }30 };

當然,由於這裡處理邊界問題比較統一,因此也可以將四個方向的移動合并到一起,通過move = [[0, 1], [1, 0], [0, -1], [-1, 0]]數組控制移動。

 1 class Solution 2 { 3 public: 4     vector<vector<int> > generateMatrix(int n) 5     { 6         vector<vector<int> > vvi(n, vector<int>(n, 0)); 7          8         if(n < 1) 9             return vvi;10         11         int move[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };12         13         int x = 0, y = 0, k = 1;14         vvi[0][0] = k;15         while(k < n * n)16             for(int i = 0; i < 4; ++ i)17                 while(x + move[i][0] >= 0 && x + move[i][0] < n &&18                       y + move[i][1] >= 0 && y + move[i][1] < n &&19                       vvi[x + move[i][0]][y + move[i][1]] == 0)20                     vvi[x += move[i][0]][y += move[i][1]] = ++ k;21         22         return vvi;23     }24 };

轉載請說明出處:LeetCode --- 59. 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.