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]
]
Problem Solving Ideas:
Refer to Java for Leetcode 054 Spiral Matrix, modify the following code, Java implementation is as follows:
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++) ma Trix[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; }
Java for Leetcode 059 Spiral Matrix II