[Note] Matrix

Posted by 西维蜀黍的OJ Blog on 2023-09-10, Last Modified on 2024-01-26

题目

解析

54. Spiral Matrix

# - time: O(m*n)
# - space: O(1)
	def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
		# current valid search range: col: [left, right], row: [top, bottom]
		# this means that "while left <= right and top <= bottom"
		left, right = 0, len(matrix[0]) - 1
		top, bottom = 0, len(matrix) - 1

		res = []
		while left <= right and top <= bottom:
			# get every element in the top row
			for i in range(left, right + 1):
				res.append(matrix[top][i])
			top += 1  # to exclude the top row

			# get every element in the right col
			for i in range(top, bottom + 1):
				res.append(matrix[i][right])
			right -= 1

			# [[1,2,3]] or [[1], [2], [3]]
			if left > right or top > bottom:
				break

			# get every element in the bottom row
			for i in range(right, left - 1, -1):
				res.append(matrix[bottom][i])
			bottom -= 1

			# get every element in the left col
			for i in range(bottom, top - 1, -1):
				res.append(matrix[i][left])
			left += 1

		return res

ref