码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode59 Spiral Matrix II

时间:2016-09-20 00:08:55      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

For example,
Given n = 3,

You should return the following matrix: (Medium)

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

分析:

跟 Sprial Matrix I处理方式一样,先建立好n * n的数组,然后按照顺时针顺序填入数字即可。

代码:

 1 class Solution {
 2 public:
 3     vector<vector<int>> generateMatrix(int n) {
 4         vector<vector<int>> result(n, vector<int>(n,0));
 5         int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1;
 6         int count = 1;
 7         while (rowBegin <= rowEnd && colBegin <= colEnd) {
 8             for (int i = colBegin; i <= colEnd; ++i ) {
 9                 result[rowBegin][i] = count;
10                 count++;
11             }
12             rowBegin++;
13             if (rowBegin > rowEnd) {
14                 break;
15             }
16             for (int i = rowBegin; i <= rowEnd; ++i) {
17                 result[i][colEnd] = count;
18                 count++;
19             }
20             colEnd--;
21             if (colBegin > colEnd) {
22                 break;
23             }
24             for (int i = colEnd; i >= colBegin; --i) {
25                 result[rowEnd][i] = count;
26                 count++;
27             }
28             rowEnd--;
29             if (rowBegin > rowEnd) {
30                 break;
31             }
32             for (int i = rowEnd; i>= rowBegin; --i) {
33                 result[i][colBegin] = count;
34                 count++;
35             }
36             colBegin++;
37         }
38         return result;
39     }
40 };

 

LeetCode59 Spiral Matrix II

标签:

原文地址:http://www.cnblogs.com/wangxiaobao/p/5886924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!