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

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

你可能感兴趣的:(Matrix)