leetcode----54. Spiral Matrix

链接:

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

大意:

给定一个二维数组,对数组进行螺旋遍历(具体什么是螺旋遍历,请看例子)。例子:

思路:

与之前的二维数组顺时针旋转90度类似:https://blog.csdn.net/smart_ferry/article/details/88820560

也是从最外围往内遍历 ,具体思路看代码及注释。

代码:

class Solution {
    public List<Integer> spiralOrder(int[][] m) {
        LinkedList<Integer> res = new LinkedList<>();
        if (m.length == 0)
            return res;
        helper(0, m.length - 1, 0, m[0].length - 1, m, res);
        return res;
    }
    public void helper(int rowStart, int rowEnd, int colStart, int colEnd, int[][] m, LinkedList<Integer> res) {
        // rowStart > rowEnd 或者 colStart > colEnd 时  直接跳出递归
        if (rowStart > rowEnd || colStart > colEnd)
            return ;
        // 只剩下同一行的数据
        if (rowStart == rowEnd) {
            while (colStart <= colEnd) {
                res.addLast(m[rowStart][colStart++]);
            }
            return ;
        }
        // 只剩下同一列的数据
        if (colStart == colEnd) {
            while (rowStart <= rowEnd) {
                res.addLast(m[rowStart++][colStart]);
            }
            return ;
        }
        // 螺旋遍历  
        // 首先在起始行rs 遍历元素为[cs,ce) 再在末尾列ce  遍历元素为[rs,re) 再在末尾行re  遍历元素为[ce,cs)  再在起始列 遍历元素为[re,rs)
        int rs = rowStart, re = rowEnd, cs = colStart, ce = colEnd;
        while (cs < ce) {
            res.addLast(m[rs][cs++]);
        }
        cs = colStart;
        while (rs < re) {
            res.addLast(m[rs++][ce]);
        }
        rs = rowStart;
        while (ce > cs) {
            res.addLast(m[re][ce--]);
        }
        ce = colEnd;
        while (re > rs) {
            res.addLast(m[re--][cs]);
        }
        re = rowEnd;
        helper(rs + 1, re - 1, cs + 1, ce - 1, m, res);
    }
}

结果:

结论:

自我感觉,思路很清晰,代码写起来也只不过是敲键盘的事。

唯一可能觉得需要改进的应该就是代码的冗余度了吧 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值