1 Star 0 Fork 0

wd6/LeetCode-1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
spiral-matrix.py 1.40 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 11年前 . update
# Time: O(m * n)
# Space: O(1)
#
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
#
# For example,
# Given the following matrix:
#
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# You should return [1,2,3,6,9,8,7,4,5].
#
class Solution:
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
result = []
if matrix == []:
return result
left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
while left <= right and top <= bottom:
for j in xrange(left, right + 1):
result.append(matrix[top][j])
for i in xrange(top + 1, bottom):
result.append(matrix[i][right])
for j in reversed(xrange(left, right + 1)):
if top < bottom:
result.append(matrix[bottom][j])
for i in reversed(xrange(top + 1, bottom)):
if left < right:
result.append(matrix[i][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return result
if __name__ == "__main__":
print Solution().spiralOrder([[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]])
print Solution().spiralOrder([[2,3]])
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wd6/LeetCode-1.git
git@gitee.com:wd6/LeetCode-1.git
wd6
LeetCode-1
LeetCode-1
master

搜索帮助