在接受微软的采访时,我得到了这个问题。
这个问题叫做2D蛇。我想知道我的解决方案1是否通过了测试,但我的解决方案1是否与解决方案2不同。
让我们一起玩2D矩阵吧!编写一个方法
find_spiral,以顺时针螺旋顺序遍历in的2D矩阵(列表列表),并将元素附加到整数的输出列表中。示例:输入矩阵:输出列表:
def find_spiral(matrix):
output = []
while matrix:
row = matrix.pop(0)
output.extend(row)
matrix = zip(*matrix)[::-1]
return outputdef find_spiral(matrix):
spiral_list = []
if matrix == None or len(matrix) == 0:
return list
m = len(matrix)
n = len(matrix[0])
x=0
y=0
while(m>0 and n>0):
if(m==1):
i = 0
while i < n:
spiral_list.append(matrix[x][y])
i += 1
y += 1
break
elif(n==1):
i = 0
while i < m:
spiral_list.append(matrix[x][y])
i += 1
x += 1
break
i = 0
while i < n-1:
spiral_list.append(matrix[x][y])
i+=1
y+=1
j = 0
while j < m-1:
spiral_list.append(matrix[x][y])
j+=1
x+=1
i = 0
while i < n-1:
spiral_list.append(matrix[x][y])
i+=1
y-=1
j = 0
while j < m-1:
spiral_list.append(matrix[x][y])
j+=1
x-=1
x+=1
y+=1
m=m-2
n=n-2
return spiral_list测试用例:
Input
[[1,2],[3,4]]
Expected Result
[1, 2, 4, 3]
Input
[[1,2],[3,4]
Expected Result
[1, 2, 4, 3]
Input
[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Expected Result
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
input
[[1,2],[3,4]
Expected Result
[1, 2, 3, 4, 5, 6, 12, 18, 17, 16, 15, 14, 13, 7, 8, 9, 10, 11]
Input
[[1,0],[0,1]]
Expected Result
[1, 0, 1, 0]
Input
[[1,2,3],[4,5,6],[7,8,9]]
Expected Result
[1, 2, 3, 6, 9, 8, 7, 4, 5]发布于 2018-01-22 14:17:41
只是回顾解决方案1。
matrix。这对调用者来说是令人惊讶的,并且可能会使其更难使用或测试。list(zip(...))。由于Python2.7是接近生命的尽头,所以编写易于移植到Python3的代码是个好主意。在本例中,您可以从future_builtins导入zip中获得与Python3兼容的内置zip函数的版本。di, dj = dj, -di是否实现了这一点。应该清楚的是,这不会修改matrix,并根据需要在\$O(n^2)\$中运行。https://codereview.stackexchange.com/questions/185626
复制相似问题