Remove Duplicates from Sorted Array II @ LeetCode (Python)
Spiral Matrix II @ LeetCode (Python)

Spiral Matrix @ LeetCode (Python)

kitt posted @ 2014年3月22日 17:46 in LeetCode , 3157 阅读

使用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.

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  

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter