Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:Given n =
3
,[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Solution:
The idea is from the origin, move right, down, left, and up while inserting an increment number to the corresponding position.
We should be careful with the boundary.
Code:
public class Solution { public int[][] generateMatrix(int n) { if (n == 0) { return new int[0][0]; } int[][] result = new int[n][n]; int num = 1; int left = 0; int right = n - 1; int top = 0; int bottom = n - 1; while (num <= n * n) { for (int j = left; j <= right; j++) { if (result[top][j] != 0) { break; } result[top][j] = num++; } top++; for (int i = top; i <= bottom; i++) { if (result[i][right] != 0) { break; } result[i][right] = num++; } right--; for (int j = right; j >= left; j--) { if (result[bottom][j] != 0) { break; } result[bottom][j] = num++; } bottom--; for (int i = bottom; i >= top; i--) { if (result[i][left] != 0) { break; } result[i][left] = num++; } left++; } return result; } }