Leetcode -- Spiral Matrix
来源:互联网 发布:阿里云企业邮箱桌面版 编辑:程序博客网 时间:2024/05/23 02:04
https://oj.leetcode.com/problems/spiral-matrix/
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].
public List<Integer> spiralOrder(int[][] matrix)
这一题和rotate image那题其实有点类似,都是对一个二维数组进行从外围到内的阅读操作。其实也可以用二重for循环来做。但是这里我采取的是另一种方法,为的是让答案显得更加直观。可以想象有上下左右四堵墙,按照下往上走一格(自左向右输出最下一行),右往左走一格(自下往上输出最右一列),上往下走一格(自右往左输出最上面一行),左往右走一格(自上往下输出最左一列)这样循环来进行,直到任意两堵墙相遇便表示输出结束了。这样会显得更加容易理解。下面是代码:
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new LinkedList<Integer>(); if(matrix.length == 0 || matrix[0].length == 0) return res; int left = 0, right = matrix[0].length - 1, bot = 0, top = matrix.length - 1; while(true){ int curleft = left; while(curleft <= right){ res.add(matrix[bot][curleft]); curleft++; } bot++; if(bot > top) break; int curbot = bot; while(curbot <= top){ res.add(matrix[curbot][right]); curbot++; } right--; if(left > right) break; int curright = right; while(curright >= left){ res.add(matrix[top][curright]); curright--; } top--; if(bot > top) break; int curtop = top; while(curtop >= bot){ res.add(matrix[curtop][left]); curtop--; } left++; if(left > right) break; } return res; }
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
- Android ProgressBar自定义图片进度,自定义渐变色进度条
- JSP中分页技术的实现(jstl,servlet,javabean三种不同实现方式)
- 数组盛水问题
- 搜索引擎的学习1
- spring mvc 如何实现全局的异常处理?
- Leetcode -- Spiral Matrix
- Java中的类锁与对象锁
- C/C++中的日期和时间
- 小马哥------高仿红米note m8207 刷机 m8207 2015新版机型拆机完美图与开机识别图
- 罗伯特议事规则
- Same Tree
- Initrd启动及功能分析
- 在oracle中用like模糊搜索时如何使其能搜到空值
- 【图像处理】MATLAB图像处理_IPC图像处理流程