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

#Leetcode# 59. Spiral Matrix II

时间:2019-01-27 16:39:33      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:leetcode   problems   spi   input   etc   href   for   sans   led   

https://leetcode.com/problems/spiral-matrix-ii/

 

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

Example:

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

代码:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int up = 0, down = n - 1, left = 0, right = n - 1, val = 1;
        while (true) {
            for (int j = left; j <= right; ++j) res[up][j] = val++;
            if (++up > down) break;
            for (int i = up; i <= down; ++i) res[i][right] = val++;
            if (--right < left) break;
            for (int j = right; j >= left; --j) res[down][j] = val++;
            if (--down < up) break;
            for (int i = down; i >= up; --i) res[i][left] = val++;
            if (++left > right) break;
        }
        return res;
    }
};

  

快一周不学习罪恶感 upup

FHFHFH

#Leetcode# 59. Spiral Matrix II

标签:leetcode   problems   spi   input   etc   href   for   sans   led   

原文地址:https://www.cnblogs.com/zlrrrr/p/10326384.html

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