class Solution { public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; int start = 0; int startNum = 1; while (2 * start < n) { int endX = n - 1 - start; int endY = n - 1 - start; for (int i = start; i <= endX; i++) { matrix[start][i] = startNum++; } if (start < endY) { for (int i = start + 1; i <= endY; i++) { matrix[i][endX] = startNum++; } } if (start < endX && start < endY) { for (int i = endY - 1; i >= start; i--) { matrix[endY][i] = startNum++; } } if (start < endX && start < endY - 1) { for (int i = endX - 1; i >= start + 1; i--) { matrix[i][start] = startNum++; } } ++start; } return matrix; }}