54. Spiral Matrix

螺旋数组,当时腾讯的在线笔试倒数第二题,想想真~~~

Spiral Matrix

题意
这里写图片描述
使用递归,一次扫描一整圈,然后用x,y记录这个圈的左上角,递归完了都+1。rows, cols记录还没扫的有多少。思想比较简单,但相当容易出错。提交了好多次。
注意:1. 扫描第一行跟最后一行要扫到底部为止,而扫描左列和右列只需要扫中间的。

1 2 3 4
5 6 7 8
9 10 11 12

例如以上例子: 你要 先扫1234, 然后是8,然后是12 11 10 9 然后是 5.
不能这样:123, 4 8, 12 11 10 , 9 5。 用后者的方法在只有一个数字 1的时候 就完全不会扫到它。

代码

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

        helper(matrix, 0, 0, matrix.length, matrix[0].length, res);

        return res;
    }

    public void helper(int[][] matrix, int x, int y, int rows, int cols, List<Integer> res){
        if(rows <= 0 || cols <= 0){
            return;
        }
        // first line
        for(int i = 0; i < cols; i++){
            res.add(matrix[x][y + i]);
        }
        // right column
        for(int i = 1; i < rows - 1; i++){
            res.add(matrix[x + i][cols - 1 + y]);
        }
        // down row
        if(rows > 1){
            for(int i = cols - 1; i >= 0; i--){
                res.add(matrix[x + rows - 1][y + i]);
            }
        }
        // left column. GO UP
        if(cols > 1){
            for(int i = rows - 2; i > 0; i--){
                res.add(matrix[x + i][y]);
            }
        }
        helper(matrix, x+1, y+1, rows-2, cols-2, res);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值