Spiral Matrix(**)

题目: 螺旋化输出矩阵
For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

思路: 递归
1. 以一圈为一次递归 比如上面的 1 2 3 6 9 8 7 4
2. 设置四个指针 top base left right
3. 四个for 取得四边的所有点 (方法有点二)

public class Solution {
   public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<> ();
        if(matrix == null || matrix.length == 0) return res;
        spirial(matrix , 0 , res);
        return res;
    }

    static void spirial(int[][] matrix , int count , List<Integer> res) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int top = count;
        int right = cols - count - 1;
        int left = count;
        int base = rows - count - 1;
// 递归出口         
        if(top > base || right < 0 || left >= cols || left > right) return ;

        if(top == base) {
            for(int i = left ; i <= right ; i++) {
                res.add(matrix[top][i]);
            }
            return ;
        }
        //上
        for(int i = count ; i < right ; i++) {
            res.add(matrix[count][i]);
        }
        //右
        for(int i = top ; i < base ; i++) {
            res.add(matrix[i][right]);
        }
        // 下
        for(int i = right ; i > left ; i--) {
            res.add(matrix[base][i]);
        }
        //左
        for(int i = base ; i > top ; i--) {
            res.add(matrix[i][left]);
            if(left == right) {
                break;
            }
        }
        spirial(matrix , count + 1 , res);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值