螺旋算法

螺旋算法


算法題目

題來源–LeetCode(https://leetcode-cn.com/problems/spiral-matrix)

給定一個包含 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]

算法分析

既然矩形,我們先拋開題目提到的螺旋,想象成下面這樣一層層去遍歷

想象成一圈一圈的矩形

取到左上點(row1,column1)和右下點(row2,column2),然後根據題目要求的順序,依次遍歷一圈後,將左上點和右下點向圈全移動成(row1+1,column1+1)和(row2-1,column2-1),再次遍歷知道遍歷完

算法

class Solution {
     public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        //先攔截異常情況
        if (matrix == null || matrix.length == 0)
            return result;
        //初始化外圈左上點(row1,column1)和右下點(row2,column2)
        int row1 = 0;
        int row2 = matrix.length - 1;
        int column1 = 0;
        int column2 = matrix[0].length - 1;
        //層層遍歷
        while (row1 <= row2 && column1 <= column2) {
            //上行
            for (int i = column1; i <= column2; i++) {
                result.add(matrix[row1][i]);
            }
            //右列
            for (int i = row1 + 1; i <= row2; i++) {
                result.add(matrix[i][column2]);
            }
            //防止剩下最後一圈時,重複輸出的問題
            if(column1<column2 && row1<row2) {
                //下行
                for (int i = column2 - 1; i >= column1; i--) {
                    result.add(matrix[row2][i]);
                }
                //左列
                for (int i = row2 - 1; i >= row1 + 1; i--) {
                    result.add(matrix[i][column1]);
                }
            }
            //將左上點和右下點向圈全移動成(row1+1,column1+1)和(row2-1,column2-1)
            row1++;
            column1++;
            row2--;
            column2--;
        }
        return result;
    }
}

後言

還有一種解法是根據觀察方向-順時針轉換方案,記錄轉換方向和是否遍歷過,到達遍歷過的點就切換方向,算法我這裏就暫時不貼出來了,有興趣的可以自己嘗試寫寫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章