LeetCode(螺旋矩陣)-模擬旋轉

20200403

題目 :螺旋矩陣

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

示例:

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

思路 :繪製螺旋軌跡路徑,當發現軌跡超出界限或者進入之前訪問過的單元格,就順時針旋轉方向。

code

class Solution{
    public List<Integer> spiralOrder(int[][] matrix){
        List<Integer> ans = new ArrayList<>();
        if(matrix.length == 0) return ans;
        int R = matrix.length;
        int C = matrix[0].length;
        boolean[][] seen = new boolean[R][C];
        int[] dr = {0,1,0,-1};
        int[] dc = {1,0,-1,0}
        int r = 0, c = 0, di = 0;
        for(int i=0;i<R*C;i++){
            ans.add(matrix[r][c]);
            seen[r][c] = true;
            int cr = r + dr[di];
            int cc = c + dr[di];
            if(0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]){
                r = cr;
                c = cc;
            }else{
                di = (di + 1)%4;
                r += dr[di];
                c += dc[di];
            }
        }
        return ans;
    }
}

複雜度分析

  • 時間複雜度:O(N)O(N)
  • 空間複雜度:O(N)O(N)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章