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 ] ]
生成的过程为 (1) 横向生成 1,2
(2) 纵向生成 3,4
(3) 横向生成 5,6
(4) 纵向生成 7,8
(5) 生成 9
public class Solution { public int[][] generateMatrix(int n) { if(n <= 0) return new int[0][]; int[][] matrix = new int[n][n]; printCircle(matrix, 0, n, 1); return matrix; } private void printCircle(int[][] matrix, int start, int end, int n) { if(start >= end) return; if(end - start == 1){ matrix[start][start] = n; return; } for(int i = start; i < end - 1; i++) { matrix[start][i] = n; n++; } for(int i = start; i < end - 1; i++) { matrix[i][end - 1] = n; n++; } for(int i = end - 1; i > start; i--) { matrix[end - 1][i] = n; n++; } for(int i = end - 1; i > start; i--) { matrix[i][start] = n; n++; } printCircle(matrix, start+1, end-1, n); } }