本文共 664 字,大约阅读时间需要 2 分钟。
Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]Java代码:
public class Solution { public int[][] generateMatrix(int n) { int[][] ans = new int[n][n]; int curr = 1; for (int i = 0, j = 0; i<(n+1)/2 ; ++i, ++j){ for (int k = j; k=n/2) break; // this is needed for odd n's. for (int k = i+1; k j; --k){ ans[n-1-i][k] = curr++; } for (int k = n-1-i; k>i; --k){ ans[k][j] = curr++; } } return ans;}}
转载地址:http://biuni.baihongyu.com/