【基础入门题071】螺旋矩阵

x33g5p2x  于2022-01-09 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(307)

【基础入门题】2022.01.06

创建一个m行n列的矩阵,将整数1至m*n从左上角分别以顺时针、逆时针方向螺旋填入矩阵。

如: m,n = 4,6,输出:
顺时针排列:
   1   2   3   4   5   6
 16 17 18 19 20  7
 15 24 23 22 21  8
 14 13 12 11 10  9

逆时针排列:
  1 16 15 14 13 12
  2 17 24 23 22 11
  3 18 19 20 21 10
  4   5   6   7   8   9

编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道   

输出时用了2种不同方法:

  1. m,n = map(int, input('请输入矩阵的行和列(用空格隔开):').split())
  2. print('\n顺时针排列:')
  3. Array = [[0 for _ in range(n)] for _ in range(m)]
  4. Array[0][0] = 1
  5. i,j,k = 0,0,1
  6. while k<m*n:
  7. while j+1<n and not Array[i][j+1]:
  8. j += 1
  9. k += 1
  10. Array[i][j] = k
  11. while i+1<m and not Array[i+1][j]:
  12. i += 1
  13. k += 1
  14. Array[i][j] = k
  15. while j and not Array[i][j-1]:
  16. j -= 1
  17. k += 1
  18. Array[i][j] = k
  19. while i and not Array[i-1][j]:
  20. i -= 1
  21. k += 1
  22. Array[i][j] = k
  23. w = len(str(m*n))+1
  24. for a in Array:
  25. for b in a:
  26. print(str(b).rjust(w), end='')
  27. print()
  28. print('\n逆时针排列:')
  29. Array = [[0 for _ in range(n)] for _ in range(m)]
  30. Array[0][0] = 1
  31. i,j,k = 0,0,1
  32. while k<m*n:
  33. while i+1<m and not Array[i+1][j]:
  34. i += 1
  35. k += 1
  36. Array[i][j] = k
  37. while j+1<n and not Array[i][j+1]:
  38. j += 1
  39. k += 1
  40. Array[i][j] = k
  41. while i and not Array[i-1][j]:
  42. i -= 1
  43. k += 1
  44. Array[i][j] = k
  45. while j and not Array[i][j-1]:
  46. j -= 1
  47. k += 1
  48. Array[i][j] = k
  49. #w = len(str(m*n))+1
  50. for a in Array:
  51. for b in a:
  52. print(f'{b:>{w}}', end='')
  53. print()

C语言代码:

  1. #include<stdio.h>
  2. int main()
  3. {
  4. int m,n,x=0,y=0,c=1;
  5. scanf("%d %d",&m,&n);
  6. int a[m+1][n+1]={0},b[m+1][n+1]={0};
  7. a[0][0]=1;b[0][0]=1;
  8. printf("顺时针排列:\n");
  9. while(c!=m*n){
  10. while(y+1<n&&!a[x][y+1]) a[x][++y]=++c;
  11. while(x+1<m&&!a[x+1][y]) a[++x][y]=++c;
  12. while(y&&!a[x][y-1]) a[x][--y]=++c;
  13. while(x&&!a[x-1][y]) a[--x][y]=++c;
  14. }
  15. for(x=0;x<m;x++){
  16. for(y=0;y<n;y++)
  17. printf("%3d", a[x][y]);
  18. printf("\n");
  19. }
  20. x=0;y=0;c=1;
  21. printf("逆时针排列:\n");
  22. while(c!=m*n){
  23. while(x+1<m&&!b[x+1][y]) b[++x][y]=++c;
  24. while(y+1<n&&!b[x][y+1]) b[x][++y]=++c;
  25. while(x&&!b[x-1][y]) b[--x][y]=++c;
  26. while(y&&!b[x][y-1]) b[x][--y]=++c;
  27. }
  28. for(x=0;x<m;x++){
  29. for(y=0;y<n;y++)
  30. printf("%3d", b[x][y]);
  31. printf("\n");
  32. }
  33. }

相关文章