[Leetcode] 54. Spiral Matrix

Link: https://leetcode.com/problems/spiral-matrix/

Solution 1:
记录matrix已经走过的row和col并进行标记

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        
        if(matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        
        int rowBegin = 0, rowEnd = matrix.length-1, colBegin = 0, colEnd = matrix[0].length-1;
        while(rowBegin <= rowEnd && colBegin <= colEnd) {
            for(int i=colBegin; i<=colEnd; i++){ // right
                res.add(matrix[rowBegin][i]);
            }
            rowBegin++;
            
            for(int i=rowBegin; i<=rowEnd; i++) { // down
                res.add(matrix[i][colEnd]);
            }
            colEnd--;
            
            if(rowBegin <= rowEnd && colBegin <= colEnd) { //重要,否则会存在begin已经超过end的情况
                for(int i=colEnd; i>=colBegin; i--) { // left
                    res.add(matrix[rowEnd][i]);
                }
                rowEnd--;
            }
            
            if(rowBegin <= rowEnd && colBegin <= colEnd) { //重要,否则会存在begin已经超过end的情况
                for(int i=rowEnd; i>=rowBegin; i--) { // up
                    res.add(matrix[i][colBegin]);
                }
                colBegin++;
            }
        }
        return res;
    }
}

TC: O(M*N)
SC: O(n)
reference: https://www.youtube.com/watch?v=3joo9yAZVh8&t=3s

Solution 2:
利用坐标控制数字的行动方向

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if(matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        
        int R = matrix.length, C = matrix[0].length;
        boolean[][] seen = new boolean[R][C];
        // row和col的行动方向控制
        int row[] = {0, 1, 0, -1};
        int col[] = {1, 0, -1, 0};
        int r = 0, c = 0, di = 0;
        
        for(int i=0; i<R*C; i++) {
            res.add(matrix[r][c]);
            seen[r][c] = true;
            // 此处暂存r和c,等判断该位置没有超出矩阵边界/到达矩阵拐点
            // 则可以加入结果中,否则就拐
            int tr = r + row[di];
            int tc = c + col[di];
            if(tr>=0 && tr<R && tc>=0 && tc<C && !seen[tr][tc]) {
                r = tr;
                c = tc;
            }else{
                di = (di+1)%4;
                r = r + row[di];
                c = c + col[di];
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值