Given an n x n
array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.python
array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:shell
array = [[1,2,3], [8,9,4], [7,6,5]] snail(array) #=> [1,2,3,4,5,6,7,8,9]
This image will illustrate things more clearly:markdown
NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.app
NOTE 2: The 0x0 (empty matrix) is represented as [[]]我好像最後仍是沒考慮空矩陣的處理。。。啊啊啊啊,路漫漫啊
ide
忽然給我來了道4kyu....寫了半天寫了一長串,結果答案裏別人一句就寫完了。。。一句。。個人心裏是崩潰的函數
Python,先貼別人的以便學習,第一個方案真是巧妙啊,服。每次遞歸取第一行,經過zip(*array[1:])將剩下的行列轉換,經過[::-1]倒序輸出爲snail的argument,就又能夠取第一行了!學習
方案3思想和方案1一致,可是表達得直觀,更適合我等菜鳥學習。this
1 #方案1 2 def snail(array): 3 return list(array[0]) + snail(zip(*array[1:])[::-1]) if array else []
1 #方案2 2 def snail(array): 3 ret = [] 4 if array and array[0]: 5 size = len(array) 6 for n in xrange((size + 1) // 2): 7 for x in xrange(n, size - n): 8 ret.append(array[n][x]) 9 for y in xrange(1 + n, size - n): 10 ret.append(array[y][-1 - n]) 11 for x in xrange(2 + n, size - n + 1): 12 ret.append(array[-1 - n][-x]) 13 for y in xrange(2 + n, size - n): 14 ret.append(array[-y][n]) 15 return ret
#方案3 def snail(array): a = [] while array: a.extend(list(array.pop(0))) array = zip(*array) array.reverse() return a
方案3注意 extend,非 append。extend 的參數是 list.idea
下面是我本身的。。。徹底沒用到 python 高效的東西,只用了最最基本的函數,太弱智了spa
1 #爲方便本地調試,加了不少 print,提交的時候須要註釋掉 2 def snail(array): 3 ans = [] 4 if len(array) == 1: # preven "index out of range"!!! 5 ans = array[0] 6 #print ans 7 return ans 8 len_row = len(array) - 1 9 len_col = len(array[1]) - 1 10 all = (len_row + 1) * (len_col +1 ) 11 #print len_col 12 over_row = 0 13 over_col = 0 14 while over_col <= len_col/2: 15 row = over_row # current row 16 col = over_col 17 while over_col <= col < len_col - over_col: 18 now = array[row][col] 19 ans.append(now) 20 col += 1 21 #print 'now == ', now 22 #print 'this row over, col ==', col 23 24 while over_row <= row < len_row - over_row : 25 now = array[row][col] 26 ans.append(now) 27 row += 1 28 #print 'now == ', now 29 #print 'this col over, row ==', row 30 31 while over_col < col <= len_col - over_col: 32 now = array[row][col] 33 ans.append(now) 34 col -= 1 35 #print 'now == ', now 36 #print 'this reverse row over, col ==', col 37 38 while over_row < row <= len_row - over_row: 39 now = array[row][col] 40 ans.append(now) 41 row -= 1 42 #print 'now == ', now 43 #print 'this reverse col over, col ==', row 44 45 over_row += 1 46 over_col += 1 47 #print 'print over_row == ', over_row, 'print over_col == ', over_col 48 if len(ans) < all: 49 last = int(len_row/2) 50 ans.append(array[last][last]) 51 #print ans 52 return ans