Spiral Matrix
来源:互联网 发布:彩票开奖数据接口 编辑:程序博客网 时间:2024/05/16 15:44
Given a matrix ofmn elements (mrows, 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 ]
]
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].
invariant: 任何时候都对应一个当前有效的上、下、左、右的界。 在当前上、下、左、右界内依次输出每条边,同时更新相应的界,如果上下界或者左右界交错,算法结束。
def spiralOrder(matrix): res = [] startX, endX, startY, endY = 0, len(matrix[0]) - 1, 0, len(matrix) - 1 while True: for j in xrange(startX, endX + 1): res.append(matrix[startY][j]) startY += 1 if startY > endY: break for i in xrange(startY, endY + 1): res.append(matrix[i][endX]) endX -= 1 if startX > endX: break for j in xrange(endX, startX - 1, -1): res.append(matrix[endY][j]) endY -= 1 if startY > endY: break for i in xrange(endY, startY - 1, -1): res.append(matrix[i][startX]) startX += 1 if startX > endX: break return res;
0 0
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- Spiral Matrix
- android 自定义控件之滑动按钮
- [03] 使用 MVC 5 的 EF6 Code First 入门 系列:排序、筛选和分页
- 统一通信的发展趋势分析
- [04] 使用 MVC 5 的 EF6 Code First 入门 系列:MVC程序中实体框架的连接恢复和命令拦截
- ExpandableListView(三)只展开一个group,没有child不展开group
- Spiral Matrix
- Linux core dump
- Android平台调用WebService详解
- iOS 上常用的两个功能:点击屏幕和return退出隐藏键盘和解决虚拟键盘挡住UITextField的方法
- Android EditText控件
- [05] 使用 MVC 5 的 EF6 Code First 入门 系列:MVC程序中实体框架的Code First迁移和部署
- spring IOC 和 DI的意义
- java内部类回顾之静态内部类
- ios异常捕获