面试中遇到一个题:
将一个二维数组螺旋循环输出,二维数组的宽和高并不一定相等。例:
[1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12]
[13, 14, 15, 16, 17, 18]
[19, 20, 21, 22, 23, 24]
[25, 26, 27, 28, 29, 30]
[31, 32, 33, 34, 35, 36]
[37, 38, 39, 40, 41, 42]
输出格式为:
1 2 3 4 5 6 12 18 24 30 36 42 41 40 39 38 37 31 25 19 13 7 8 9 10 11 17 23 29 35 34 33 32 26 20 14 15 16 22 28 27 21
由python实现:
'''Created on 2016年4月11日'''
def double_list_screw(source_list):
#每层有四种遍历情况,上下左右,分别处理输出
h_len = len(source_list)
if h_len > 0:w_len = len(source_list[0])
else: w_len = 0
x_start,y_start,x_end,y_end = 0,0,w_len-1,h_len-1
while x_start <= x_end and y_start <= y_end:
for i in range(x_start,x_end + 1):
print source_list[y_start][i], y_start = y_start + 1
if y_start > y_end:break
for i in range(y_start,y_end+1):
print source_list[i][x_end], x_end = x_end - 1
for i in range(x_end,x_start-1,-1):
print source_list[y_end][i], y_end = y_end - 1
if x_start>x_end:break
for i in range(y_end,y_start-1,-1):
print source_list[i][x_start], x_start = x_start + 1
####验证代码,初始化一个m行n列的递增二维数组####
m = 6
n = 7
count = 1
s_list = []
for j in range(1,n+1):
temp = []
for i in range(1,m +1):
temp.append(count)
count = count + 1
s_list.append(temp)
####验证输出结果####
print "s_list:"
for i in s_list:
print i
double_list_screw(s_list)
算法由python实现,其中遇到的问题:除了判断while循环的x,y起始坐标是否越界,还需要判断一种特殊情况:最后一圈只剩一行或者一列,因此在while循环内部加两个判断语句。
if y_start > y_end : break
if x_start > x_end:break