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 ] ]
这道题其实就是第54题Spiral Matrix的输入和输出反过来而已。
很简单,一圈一圈往里写数据,circle 共有n/2+1圈。然后写入数据即可。
public class Solution { public int[][] generateMatrix(int n) { int[][] result = new int[n][n]; int num = n/2+1; int left = 0,right = n-1; int ans = 1; for ( int circle = 0;circle < num;circle++){ for( int i = left;i<=right;i++){ result[circle][i] = ans; ans++; } for( int i = left+1;i<=right;i++){ result[i][n-1-circle] = ans; ans++; } for( int i =right-1;i>=left;i--){ result[n-circle-1][i] = ans; ans++; } for( int i = right-1;i>left;i--){ result[i][circle] = ans; ans++; } left++; right--; } return result; } }