Advertisement
Nenogzar

matrix n * n radial

Apr 10th, 2024
942
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.01 KB | None | 0 0
  1. def printpattern(n):
  2.     matrix = [[0] * n for _ in range(n)]
  3.     num = n * n
  4.     top, botton, left, right = 0, n - 1, 0, n - 1
  5.  
  6.     while top <= botton and left <= right:
  7.         for i in range(left, right + 1):
  8.             matrix[top][i] = num
  9.             num -= 1
  10.         top += 1
  11.  
  12.         for i in range(top, botton + 1):
  13.             matrix[i][right] = num
  14.             num -= 1
  15.         right -= 1
  16.  
  17.         for i in range(right, left - 1, -1):
  18.             matrix[botton][i] = num
  19.             num -= 1
  20.         botton -= 1
  21.  
  22.         for i in range(botton, top - 1, -1):
  23.             matrix[i][left] = num
  24.             num -= 1
  25.         left += 1
  26.     return matrix
  27.  
  28.  
  29. def printMatrix(martix):
  30.     for row in matrix:
  31.         for cell in row:
  32.             print(f'{cell:2d}', end=' ')
  33.         print()
  34.  
  35.  
  36. n = int(input("матрица от кой ред? "))
  37. matrix = printpattern(n)
  38. printMatrix(matrix)
  39.  
  40. # 5
  41. # 25 24 23 22 21
  42. # 10  9  8  7 20
  43. # 11  2  1  6 19
  44. # 12  3  4  5 18
  45. # 13 14 15 16 17
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement