【MEDIUM】Spiral Matrix

发布于:2018-12-08 17:01,阅读数:527,点赞数:0


# 问题 原题链接:[https://leetcode.com/problems/spiral-matrix/](https://leetcode.com/problems/spiral-matrix/) Given a matrix of m x n elements (m rows, ncolumns), return all elements of the matrix in spiral order. Example 1: ``` Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] ``` Example 2: ``` Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7] ``` # 分析过程 - 输入:一个二维数组矩阵 - 输出:矩阵元素螺旋排列的数组 - 思路:取矩阵行数和列数,定义上下左右四个边界值,然后上下左右行/列分别输出。任意输出完一行/列,边界移动,退出条件为左右/上下边界触碰。 # 解决方法 ```swift class Solution { func spiralOrder(_ matrix: [[Int]]) -> [Int] { guard matrix.count > 0 else { return [] } // 取到矩阵的行数和列数 let m = matrix.count - 1 let n = matrix[0].count - 1 // 上下左右边界 var top = 0, bottom = m, left = 0, right = n; // 结果 var result = Array<Int>() while true { // top,从 left 到 right 输出 for i in left...right { result.append(matrix[top][i]) } // top 往下移动一行 top += 1 if top > bottom { break } // right,从 top 到 bottom 输出 for j in top...bottom { result.append(matrix[j][right]) } // right 往左移动一行 right -= 1 if right < left { break } // bottom,从 left 到 right 输出 for i in left...right { result.append(matrix[bottom][right - i + left]) } // bottom 向上移动一行 bottom -= 1 if bottom < top { break } // left,从 bottom 到 top 输出 for j in top...bottom { result.append(matrix[bottom - j + top][left]) } // left 向右移动一行 left += 1 if left > right { break } } return result } } ```


评论:0条


返回列表

返回主页