原题目
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]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
思路
右下左上迭代
第一遍解法
网上好的解法
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<Integer>();
if (matrix.length == 0) {
return res;
}
int rowBegin = 0;
int rowEnd = matrix.length-1;
int colBegin = 0;
int colEnd = matrix[0].length - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
// Traverse Right
for (int j = colBegin; j <= colEnd; j ++) {
res.add(matrix[rowBegin][j]);
}
rowBegin++;
// Traverse Down
for (int j = rowBegin; j <= rowEnd; j ++) {
res.add(matrix[j][colEnd]);
}
colEnd--;
if (rowBegin <= rowEnd) {
// Traverse Left
for (int j = colEnd; j >= colBegin; j --) {
res.add(matrix[rowEnd][j]);
}
}
rowEnd--;
if (colBegin <= colEnd) {
// Traver Up
for (int j = rowEnd; j >= rowBegin; j --) {
res.add(matrix[j][colBegin]);
}
}
colBegin ++;
}
return res;
}
}
Python 无敌吊炸天让人跪下就起不来的解法
def spiralOrder(self, matrix):
return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])
自己可以改进的地方
最简代码
获得的思考
- return a and b:对应上面 matrix 为 [] 时返回 [] 否则返回 and 后面的式子
- zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
[*matrix.pop(0)]
的解释
and 后面的表达式是列表相加的形式,递归的跳出条件是 matrix
为空,但是 matrix.pop(0)
通常是一个 tuple(因为 zip
创造了一个元组列表)。“tuple+list” 无法进行,所以需要将每一个元组转换为列表。
- and 后面的式子的运行流程
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [*matrix.pop(0)]
[1, 2, 3]
>>> matrix
[[4, 5, 6], [7, 8, 9]]
>>> *matrix,
([4, 5, 6], [7, 8, 9])
>>> zip(*matrix)
<zip object at 0x7f039fc2a848>
>>> [zip(*matrix)]
[<zip object at 0x7f039fc2a888>]
>>> [*zip(*matrix)]
[(4, 7), (5, 8), (6, 9)]
>>> [*zip(*matrix)][::-1]
[(6, 9), (5, 8), (4, 7)]
- 关于
*
相当于对 list 和 tuple 进行拆包,拆出每个元素
下面的文章很好地讲解了星号表达式