fork download
  1. /*
  2. 描述: 撰寫程式來生成並打印一個 4×4 的螺旋矩陣。螺旋矩陣是指從左上角開始填入數字1,沿著螺旋路徑填滿整個矩陣。
  3.  
  4. Description: Write a program to generate and print a 4×4 spiral matrix.
  5. A spiral matrix starts by filling in the number 1 at the top-left corner, and continues filling in numbers along a spiral path until the entire matrix is filled.
  6.  
  7. Output:
  8.  1 2 3 4
  9. 12 13 14 5
  10. 11 16 15 6
  11. 10 9 8 7
  12. */
  13.  
  14.  
  15. #include <stdio.h>
  16. int main(){
  17. int N = 4;
  18. int num = 1;
  19. int arr[4][4];
  20. int top = 0, bottom = N - 1, left = 0, right = N - 1;
  21.  
  22. while (top <= bottom && left <= right) {
  23. // filling from left to right
  24. // Write your code here
  25. top++;
  26.  
  27. // filling from top to bottom
  28. // Write your code here
  29. right--;
  30.  
  31. // filling from right to left
  32. if (top <= bottom) {
  33. // Write your code here
  34. }
  35.  
  36. // filling from bottom to top
  37. if (left <= right) {
  38. // Write your code here
  39. }
  40. }
  41.  
  42. for (int i = 0; i < N; i++) {
  43. for (int j = 0; j < N; j++) {
  44. printf("%2d ", arr[i][j]);
  45. }
  46. printf("\n");
  47. }
  48. }
Success #stdin #stdout 0.01s 5280KB
stdin
18
stdout
 0  0 15774463  0 
194  0 -948152330 32766 
 1  0 -227656875 5366 
 0  0 2081964581 21876