题目链接: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,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*
*/
public class SpiralMatrixII {
// 21 / 21 test cases passed.
// Status: Accepted
// Runtime: 208 ms
// Submitted: 0 minutes ago
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
// up
// left right
// down
int left = 0;
int right = n - 1;
int up = 0;
int down = n - 1;
int count = 0;
while(left <= right && up <= down) {
for(int i = left; i <= right; i ++) {
matrix[up][i] = (++ count);
}
up ++;
for(int i = up; i <= down; i ++) {
matrix[i][right] = (++count);
}
right --;
for(int i = right; i >= left && up <= down; i --) {
matrix[down][i] = (++count);
}
down --;
for(int i = down; i >= up && left <= right; i --) {
matrix[i][left] = (++ count);
}
left ++;
}
return matrix;
}
public static void main(String[] args) {
}
}[LeetCode 59] Spiral Matrix II
原文:http://blog.csdn.net/ever223/article/details/44542825