sidorenkov

spiral_form

Aug 14th, 2021
1,018
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def spiral_form(array):
  2.     if not array:
  3.         return
  4.  
  5.     n = len(array)
  6.     m = len(array[0])
  7.  
  8.     result = []
  9.  
  10.     left = 0  # start column index
  11.     right = m - 1  # end column index
  12.     up = 0  # start row index
  13.     down = n - 1  # end row index
  14.  
  15.     while len(result) < n * m:
  16.         for i in range(left, right + 1):
  17.             result.append(array[left][i])
  18.  
  19.         for i in range(up + 1, down + 1):
  20.             result.append(array[i][right])
  21.  
  22.         if len(result) < n * m:
  23.  
  24.             for i in range(right - 1, left - 1, -1):
  25.                 result.append(array[down][i])
  26.  
  27.             for i in range(down - 1, up, -1):
  28.                 result.append(array[i][left])
  29.  
  30.         left += 1
  31.         right -= 1
  32.         down -= 1
  33.         up += 1
  34.  
  35.     return result
RAW Paste Data