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

这题就是按顺序来一个一个写,可以借鉴之前的旋转矩阵的index的顺序,小心每一行/列的头尾,每一行/列的尾都在下一个列/行的开始之前结束。

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s