1. 程式人生 > 實用技巧 >leetcode刷題筆記五十四 螺旋矩陣

leetcode刷題筆記五十四 螺旋矩陣

leetcode刷題筆記五十四 螺旋矩陣

源地址:54. 螺旋矩陣

問題描述:

給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

示例 1:

輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例 2:

輸入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]

程式碼補充:

/**
使用按層處理矩陣的方法
以左上角即(0,0)處開始,沿 top -> right -> bottom -> left列印
外層列印完後,修改left、right、top、bottom值,進入內層列印
需要注意的是 要判斷處理單層列印情況
進行 top -> right 一側處理後, 需要判斷是否之前列印的是否為單層,若為否,則繼續列印,否則列印完成
時間複雜度:O(mn) 空間複雜度:O(1)
*/
import scala.collection.mutable
object Solution {
    def spiralOrder(matrix: Array[Array[Int]]): List[Int] = {
        if (matrix == null || matrix.length == 0 || matrix(0).length == 0) return List()
        
        val res = new mutable.ListBuffer[Int]()
        var left = 0
        var right = matrix(0).length - 1
        var top = 0
        var bottom = matrix.length - 1

        while( left <= right && top <= bottom ){
            for(col <- left to right) res += matrix(top)(col)
            for(row <- top+1 to bottom) res += matrix(row)(right)
            if(left < right && top < bottom){
                for(col <- (left+1 to right-1).reverse) res += matrix(bottom)(col)
                for(row <- (top+1 to bottom).reverse) res += matrix(row)(left)
            }
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        }
        return res.toList
    }
}