Leetcode题目分析:Spiral Matrix

54. Spiral Matrix

题目

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:
Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

分析

难度不大的一道题,只要清楚遍历矩阵时每个方向都要遍历哪些元素即可(有一个坑就是要考虑到矩阵为空的情况)
设矩阵为m*n,易得:
初始时向右遍历,行标号不变,列标号范围为[0,n)
随后向下遍历,列标号不变,行标号范围为[1,m)
向左遍历,行标号不变,列标号范围为[0,n-1)
向上遍历,列标号不变,行标号范围为[1,m-1)
按一个方向遍历完后标号范围左右两边都要减一,考虑可读性,范围可以用字典存储

代码

if not matrix: return []
m, n = len(matrix), len(matrix[0])
direction = ['R', 'D', 'L', 'U']
pathRange = {
    direction[0]: (0, n),
    direction[1]: (1, m),
    direction[2]: (0, n-1),
    direction[3]: (1, m-1)
}
row, col, d, count, res = 0, 0, 0, 0, []
while count < m*n:
    x, y = pathRange[direction[d]]
    if direction[d] == 'R':
        res.extend([matrix[row][i] for i in range(x, y)])
        col = y-1
    elif direction[d] == 'D':
        res.extend([matrix[i][col] for i in range(x, y)])
        row = y-1
    elif direction[d] == 'L':
        res.extend([matrix[row][i] for i in reversed(range(x, y))])
        col = x
    elif direction[d] == 'U':
        res.extend([matrix[i][col] for i in reversed(range(x, y))])
        row = x
    count += y - x
    pathRange[direction[d]] = x+1, y-1
    d = (d+1) % 4
return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值