Guest User

Untitled

a guest
Mar 20th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. input: inputMatrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20] ]
  2.  
  3. output: [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12]
  4.  
  5. def spiral_copy(inputMatrix):
  6. output = []
  7.  
  8. top_row = 0
  9. bottom_row = len(inputMatrix) - 1
  10. left_col = 0
  11. right_col = len(inputMatrix[0]) - 1
  12.  
  13. while top_row <= bottom_row and left_col <= right_col:
  14.  
  15. for i in range(left_col, right_col + 1):
  16. output.append(inputMatrix[top_row][i])
  17. top_row += 1
  18.  
  19. for i in range(top_row, bottom_row + 1):
  20. output.append(inputMatrix[i][right_col])
  21. right_col -= 1
  22.  
  23. if top_row > bottom_row: break
  24.  
  25. for i in range(right_col, left_col - 1, -1):
  26. output.append(inputMatrix[bottom_row][i])
  27. bottom_row -= 1
  28.  
  29. if left_col > right_col: break
  30.  
  31. for i in range(bottom_row, top_row - 1, -1):
  32. output.append(inputMatrix[i][left_col])
  33. left_col += 1
  34.  
  35. return output
Add Comment
Please, Sign In to add comment