LeetCode Spiral Matrix
来源:互联网 发布:js array pushall 编辑:程序博客网 时间:2024/05/21 22:51
LeetCode解题之Spiral Matrix
原题
将一个矩阵中的内容螺旋输出。
注意点:
- 矩阵不一定是正方形
例子:
输入: matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
输出: [1, 2, 3, 6, 9, 8, 7, 4, 5]
解题思路
控制好当前遍历的边界,不断的向内缩进。需要注意的是,缩到最里面的时候可能会出现以下几种情况:
中心剩下一个数值———|3|———中心横向多个数值—————————|3 4 5 6|—————————中心纵向多个数值———|2||3||4|———
分别处理一下即可。
AC源码
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if not matrix: return [] left = top = 0 right = len(matrix[0]) - 1 bottom = len(matrix) - 1 result = [] while left < right and top < bottom: for i in range(left, right): result.append(matrix[top][i]) for i in range(top, bottom): result.append(matrix[i][right]) for i in range(right, left, -1): result.append(matrix[bottom][i]) for i in range(bottom, top, -1): result.append(matrix[i][left]) left += 1 right -= 1 top += 1 bottom -= 1 if left == right and top == bottom: result.append(matrix[top][left]) elif left == right: for i in range(top, bottom + 1): result.append(matrix[i][left]) elif top == bottom: for i in range(left, right + 1): result.append(matrix[top][i]) return resultif __name__ == "__main__": assert Solution().spiralOrder([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) == [1, 2, 3, 6, 9, 8, 7, 4, 5] assert Solution().spiralOrder([[2], [3]]) == [2, 3] assert Solution().spiralOrder([[2, 3]]) == [2, 3]
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- [leetcode]Spiral Matrix&&Spiral Matrix II
- Leetcode:Spiral Matrix与Spiral Matrix II
- LeetCode | Spiral Matrix /Spiral Matrix II
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix
- [Leetcode] Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode] Spiral Matrix
- leetcode 80: Spiral Matrix
- [Leetcode] Spiral Matrix
- [LeetCode]Spiral Matrix
- [LeetCode]Spiral Matrix II
- Ionic基础——CSS布局
- ALAsset 的用法(时间、url 、图片的获取)
- tableview的调用方法
- iOS7崩溃报 UIView _didChangeToFirstResponder
- HDU 5605 geometry
- LeetCode Spiral Matrix
- LLDB调试命令初探
- java基础IO流之字节流
- linux的top命令参数详解
- getFragmentManager和getSupportFragmentManager的区别
- 迭代器模式
- [leetcode] 108. Convert Sorted Array to Binary Search Tree 解题报告
- ubuntu下安装kvm虚拟机
- 为什么 Android 手机总是越用越慢?