Python Solution, Based on Dirction


  • 0
    class Solution(object):
        def spiralOrder(self, matrix):
            ret = []
            if not matrix:
                return ret
    
            m, n = len(matrix), len(matrix[0])
            r, c, dirc, r_s, r_e, c_s, c_e = 0, 0, 0, 0, m, 0, n
            dircs = [[0, 1], [1, 0], [0, -1], [-1, 0]]
    
            while True:
                ret.append(matrix[r][c])
                rr, cc = r + dircs[dirc][0], c + dircs[dirc][1]
                if rr < r_s or rr >= r_e or cc < c_s or cc >= c_e:
                    if dirc == 0:
                        r_s += 1
                    elif dirc == 1:
                        c_e -= 1
                    elif dirc == 2:
                        r_e -= 1
                    else:
                        c_s += 1
    
                    if r_s == r_e or c_s == c_e:
                        break
                    dirc = (dirc + 1) % 4
                r += dircs[dirc][0]
                c += dircs[dirc][1]
    
            return ret
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.