leetcode -- Spiral Matrix -- 思路简单,但很麻烦

https://leetcode.com/problems/spiral-matrix/

思路1 循环矩阵的左上角

这里我的思路就是 以 左上角 i,j = 0,0为初始点,然后每次都从对角线下移,一直到越界或者matrix[i][j]已经在res里面。这里每次都要记录start_i, start_j,即左上角点,以及end_i, end_j右下角点。

另一个要注意的地方就是可能没有spiral,只有一条垂直线或者水平线。

if i == end_i: 
if j == end_j:

这两种情况要考虑进去。

class Solution(object):
    def spiralOrder(self, matrix):
        """ :type matrix: List[List[int]] :rtype: List[int] """
        if not matrix: return []
        m, n = len(matrix), len(matrix[0])
        #if m == 1: return matrix[0]
        #if n == 1: return [x[0] for x in matrix]
        res = []
        i,j = 0, 0
        count = 0
        while i < m and j < n and matrix[i][j] not in res:
            start_i, start_j = i, j
            end_i, end_j = m - count - 1, n - count - 1

            if i == end_i: 
                res.extend(matrix[i][start_j:end_j +1])
                break
            if j == end_j:
                for k in xrange(start_i, end_i + 1):
                    res.append(matrix[k][j])
                break

            while j<=end_j:
                res.append(matrix[i][j])
                j += 1
            j -= 1
            i += 1
            while i<=end_i:
                res.append(matrix[i][j])
                i += 1
            i -= 1
            j -= 1
            while j>=start_j:
                res.append(matrix[i][j])
                j -= 1
            j += 1
            i -= 1
            while i>start_i:#exclude the mat[i][j]
                res.append(matrix[i][j])
                i -= 1

            i, j = i + 1, j + 1
            count += 1
        return res

思路2 循环矩阵的up down left right四条边界

参考
http://www.cnblogs.com/zuoyuan/p/3769829.html
有更简单的方法

class Solution:
    # @param matrix, a list of lists of integers
    # @return a list of integers
    def spiralOrder(self, matrix):
        if matrix == []: return []
        up = 0; left = 0
        down = len(matrix)-1
        right = len(matrix[0])-1
        direct = 0  # 0: go right 1: go down 2: go left 3: go up
        res = []
        while True:
            if direct == 0:
                for i in range(left, right+1):
                    res.append(matrix[up][i])
                up += 1
            if direct == 1:
                for i in range(up, down+1):
                    res.append(matrix[i][right])
                right -= 1
            if direct == 2:
                for i in range(right, left-1, -1):
                    res.append(matrix[down][i])
                down -= 1
            if direct == 3:
                for i in range(down, up-1, -1):
                    res.append(matrix[i][left])
                left += 1
            if up > down or left > right: return res#注意这句话
            direct = (direct+1) % 4#注意这句话

你可能感兴趣的:(LeetCode)