Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; int begin = 0, end = n - 1; int num = 1; while (begin < end) { for (int j = begin; j < end; ++j) matrix[begin][j] = num++; for (int i = begin; i < end; ++i) matrix[i][end] = num++; for (int j = end; j > begin; --j) matrix[end][j] = num++; for (int i = end; i > begin; --i) matrix[i][begin] = num++; ++begin; --end; } if (begin == end) matrix[begin][begin] = num; return matrix; } }
左右
上下
右左
下上
原文:https://www.cnblogs.com/wentiliangkaihua/p/10648193.html