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