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

LeetCode 59 Spiral Matrix II 螺旋矩阵之二

时间:2018-03-25 16:58:31      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:矩阵   body   order   log   square   --   fill   spi   integer   

 

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:

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

此题跟之前那道本质上没什么区别,就相当于个类似逆运算的过程,这道题是要按螺旋的顺序来填数,由于给定矩形是个正方形,我们计算环数时用n / 2来计算,若n为奇数时,注意一下中间点。

 

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
         
        vector<vector<int>> v(n,vector<int>(n,1));
        int cnt = 1;
        int p=n; 
        for (int i=0; i<n/2; i++, p=p-2){
            for(int col=i; col < i+p; col ++){
                v[i][col] = cnt++;
            }
            for(int row=i+1; row < i+p; row++){
                v[row][i+p-1] = cnt++;
            }
            for(int col=i+p-2; col>=i; col--){
                v[i+p-1][col] = cnt++;
            }
            for(int row=i+p-2; row>i; row--){
                v[row][i] = cnt++;
            }
            
        }
        if((n%2) == 1)v[n/2][n/2] = cnt;
        return v;
    }
};

 

LeetCode 59 Spiral Matrix II 螺旋矩阵之二

标签:矩阵   body   order   log   square   --   fill   spi   integer   

原文地址:https://www.cnblogs.com/mantodream/p/8645209.html

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