fork download
  1. #include <stdio.h>
  2.  
  3. #define MAX 20
  4.  
  5. void printSpiralMatrix(int n) {
  6. int matrix[MAX][MAX];
  7. int left = 0, right = n - 1, top = 0, bottom = n - 1;
  8. int value = 1;
  9.  
  10. for (int i = 0; i < n; i++) {
  11. for (int j = 0; j < n; j++) {
  12. matrix[i][j] = 0;
  13. }
  14. }
  15.  
  16. while (value <= n * n) {
  17. for (int i = left; i <= right; i++) {
  18. matrix[top][i] = value++;
  19. }
  20. top++;
  21.  
  22. for (int i = top; i <= bottom; i++) {
  23. matrix[i][right] = value++;
  24. }
  25. right--;
  26.  
  27. if (top <= bottom) {
  28. for (int i = right; i >= left; i--) {
  29. matrix[bottom][i] = value++;
  30. }
  31. bottom--;
  32. }
  33.  
  34. if (left <= right) {
  35. for (int i = bottom; i >= top; i--) {
  36. matrix[i][left] = value++;
  37. }
  38. left++;
  39. }
  40. }
  41.  
  42. for (int i = 0; i < n; i++) {
  43. for (int j = 0; j < n; j++) {
  44. printf("%d ", matrix[i][j]);
  45. }
  46. printf("\n");
  47. }
  48. }
  49.  
  50. int main() {
  51. int n;
  52. scanf("%d", &n);
  53.  
  54. if (n > 0 && n <= 20) {
  55. printSpiralMatrix(n);
  56. }
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Standard output is empty