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 1: Simple looping code
public class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix=new int[n][n];
int lo=0, hi=n-1;
int i=1;
while (lo<hi) {
for (int k=lo; k<hi; k++) matrix[lo][k]=i++;
for (int k=lo; k<hi; k++) matrix[k][hi]=i++;
for (int k=hi; k>lo; k--) matrix[hi][k]=i++;
for (int k=hi; k>lo; k--) matrix[k][lo]=i++;
lo++;hi--;
}
if (lo==hi) matrix[lo][lo]=i++;
return matrix;
}
}
没有评论:
发表评论