LeetCode 59. Spiral Matrix II

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 ]
]

Same procedure as http://blog.csdn.net/github_34333284/article/details/51239726

#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;

vector< vector<int> > generateMatrix(int n) {
    int layer = n/2;
    int tmp = 1;

    vector< vector<int> > matrix(n, vector<int>(n, 0));

    for(int i = 0; i < layer; ++i) {
        for(int j = i; j < n - 1 - i; ++j)
            matrix[i][j] = tmp++;

        for(int j = i; j < n - 1 - i; ++j) {
            matrix[j][n - 1 - i] = tmp++;
        }

        for(int j = n - 1 - i; j > i; --j) {
            matrix[n - 1 - i][j] = tmp++;
        }

        for(int j = n - 1 - i; j > i; --j) {
            matrix[j][i] = tmp++;
        }
    }

    if(n % 2 == 1) {
        matrix[layer][layer] = tmp;
    }
    return matrix;
}

int main(void) {
    vector< vector<int> > res = generateMatrix(4);
    for(int i = 0; i < res.size(); ++i) {
        for(int j = 0; j < res[i].size(); ++j) {
            cout << setw(2) << res[i][j] << " ";
        }
        cout << endl;
    }
}


你可能感兴趣的:(LeetCode 59. Spiral Matrix II)