1. 程式人生 > >[leetcode]59. Spiral Matrix II

[leetcode]59. Spiral Matrix II

[leetcode]59. Spiral Matrix II


Analysis

intern intern intern—— [每天刷題並不難0.0]

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
在這裡插入圖片描述

Implement

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<
vector<int>> res(n, vector<int>(n)); int k = 1; int i = 0; while(k <= n*n){ int j = i; while(j < n - i) res[i][j++] = k++; j = i + 1; while(j < n - i) res[j++][n-i-1] = k++;
j = n-i-2; while(j > i) res[n-i-1][j--] = k++; j = n-i-1; while(j > i) res[j--][i] = k++; i++; } return res; } };