Leetcode 59. Spiral Matrix II

59. Spiral Matrix II

  • Total Accepted: 58954
  • Total Submissions: 162869
  • Difficulty: Medium

 

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:
 
 
思路:和Leetcode 54. Spiral Matrix类似。
 
 
代码:
 1 class Solution {
 2 public:
 3     vector<vector<int> > generateMatrix(int n) {
 4         vector<vector<int> > res(n,vector<int>(n));
 5         int i=0,j=0,cur=1;
 6         while(n>0){
 7             res[i][j]=cur++;
 8             n--;
 9             int step=n;
10             while(step>0){
11                 res[i][++j]=cur++;
12                 step--;
13             }
14             step=n;
15             while(step>0){
16                 res[++i][j]=cur++;
17                 step--;
18             }
19             if(n>0){//判断有没有剩余的半圈
20                 step=n--;//得到下一圈的n
21                 while(step>0){
22                     res[i][--j]=cur++;
23                     step--;
24                 }
25                 step=n;
26                 while(step>0){
27                     res[--i][j]=cur++;
28                     step--;
29                 }
30                 j++;
31             }
32         }
33         return res;
34     }
35 };

 

posted @ 2016-08-03 10:45  Deribs4  阅读(248)  评论(0编辑  收藏  举报