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 ]
]
解题思路:
参考Java for LeetCode 054 Spiral Matrix,修改下代码即可,JAVA实现如下:
static public int[][] generateMatrix(int n) { if(n==0) return new int[0][0]; int[][] matrix=new int[n][n]; int num=0,left = 0, right = matrix[0].length - 1, up = 0, down = matrix.length - 1; while (left <= right && up <= down) { for (int i = left; i <= right&&up<=down; i++) matrix[up][i]=++num; up++; for (int i = up; i <= down&&left<=right; i++) matrix[i][right]=++num; right--; for (int i = right; i >= left&&up<=down; i--) matrix[down][i]=++num; down--; for (int i = down; i >= up&&left<=right; i--) matrix[i][left]=++num; left++; } return matrix; }