Leetcode: Spiral Matrix II

来源:互联网 发布:jav网络机顶盒v8固件 编辑:程序博客网 时间:2024/06/16 15:21

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

Iterate over n / 2 circles. If n is odd, add n^2 at the center of the matrix. 

public class Solution {    public int[][] generateMatrix(int n) {        int[][] res = new int[n][n];        int value = 1;        for (int i = 0; i < n / 2; i++) {            for (int j = i; j < n - 1 - i; j++) {                res[i][j] = value++;            }                        for (int j = i; j < n - 1 - i; j++) {                res[j][n - 1 - i] = value++;            }                        for (int j = n - 1 - i; j > i; j--) {                res[n - 1 - i][j] = value++;            }                        for (int j = n - 1 - i; j > i; j--) {                res[j][i] = value++;            }        }                if (n % 2 == 1) {            res[n /2][n / 2] = value;        }                return res;    }}


0 0