fork download
  1. def print_spiral(matrix):
  2. if not matrix or not matrix[0]:
  3. return
  4.  
  5. top, bottom = 0, len(matrix) - 1
  6. left, right = 0, len(matrix[0]) - 1
  7.  
  8. while top <= bottom and left <= right:
  9. # Print the top row
  10. for i in range(left, right + 1):
  11. print(matrix[top][i], end=" ")
  12. top += 1
  13.  
  14. # Print the right column
  15. for i in range(top, bottom + 1):
  16. print(matrix[i][bottom], end=" ")
  17. right -= 1
  18.  
  19. if top <= bottom:
  20. # Print the bottom row
  21. for i in range(right, left - 1, -1):
  22. print(matrix[right][i], end=" ")
  23. bottom -= 1
  24.  
  25. if left <= right:
  26. # Print the left column
  27. for i in range(bottom, top - 1, -1):
  28. print(matrix[i][left], end=" ")
  29. left += 1
  30.  
  31. # Example usage:
  32. matrix = [
  33. [1, 2, 3, 4],
  34. [5, 6, 7, 8],
  35. [9, 10, 11, 12],
  36. [13, 14, 15, 16]
  37. ]
  38.  
  39. print_spiral(matrix)
Success #stdin #stdout 0.04s 9628KB
stdin
Standard input is empty
stdout
1 2 3 4 8 12 16 11 10 9 9 5 6 7 11 6