面试题29. 顺时针打印矩阵

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

func spiralOrder(_ matrix: [[Int]]) -> [Int] {
    if matrix.count <= 0 {return []}
    var left = 0
    var top = 0
    var right = matrix[0].count - 1
    var bottom = matrix.count - 1
    var result = [Int]()
    while true {
        //left->right
        for i in left...right {result.append(matrix[top][i])}
        top = top + 1
        if top > bottom {break}
        //top->bottom
        for i in top...bottom {result.append(matrix[i][right])}
        right = right - 1
        if left > right {break}
        //right->left
        for i in stride(from: right, to: left - 1, by: -1) {result.append(matrix[bottom][i])}
        bottom = bottom - 1
        if top > bottom {break}
        //bottom->top
        for i in stride(from: bottom, to: top - 1, by: -1) {result.append(matrix[i][left])}
        left = left + 1
        if left > right {break}
    }
    return result
}


你可能感兴趣的:(面试题29. 顺时针打印矩阵)