Spiral Matrix @ LeetCode (Python)
kitt
posted @ 2014年3月22日 17:46
in LeetCode
, 3186 阅读
使用0,1,2,3四个值表示方向以便切换, 用maxUp, maxDown, maxLeft, maxRight四个变量记录四个边界。当maxUp > maxDown 或 maxLeft > maxRight时就结束。
0,1,2,3 four values are used to indicates direction, maxUp, maxDown, maxLeft, maxRight four variables are used to record four boundaries. When maxUp > maxDown or maxLeft > maxRight program can return.
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 | class Solution: # @param matrix, a list of lists of integers # @return a list of integers def spiralOrder( self , matrix): if matrix = = []: return [] res = [] maxUp = maxLeft = 0 maxDown = len (matrix) - 1 maxRight = len (matrix[ 0 ]) - 1 direct = 0 # 0 go right, 1 go down, 2 go left, 3 go up while True : if direct = = 0 : # go right for i in xrange (maxLeft, maxRight + 1 ): res.append(matrix[maxUp][i]) maxUp + = 1 elif direct = = 1 : # go down for i in xrange (maxUp, maxDown + 1 ): res.append(matrix[i][maxRight]) maxRight - = 1 elif direct = = 2 : # go left for i in reversed ( xrange (maxLeft, maxRight + 1 )): res.append(matrix[maxDown][i]) maxDown - = 1 else : # go up for i in reversed ( xrange (maxUp, maxDown + 1 )): res.append(matrix[i][maxLeft]) maxLeft + = 1 if maxUp > maxDown or maxLeft > maxRight: return res direct = (direct + 1 ) % 4 |
2023年4月23日 06:35
crediblebh