面试题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
}


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容