54. 螺旋矩阵

54. 螺旋矩阵

题目

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

代码

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order=new ArrayList<Integer>();
        if(matrix==null)
            return order;
        int rows=matrix.length,cols=matrix[0].length;
        boolean[][] visted=new boolean[rows][cols];
        int total=rows*cols;
        int row=0,col=0;
        int[][] directions={{0,1},{1,0},{0,-1},{-1,0}};
        int directionsIndex=0;
        for(int i=0;i<total;i++){
            order.add(matrix[row][col]);
            visted[row][col]=true;
            int nextrow=row+directions[directionsIndex][0],nextcol=col+directions[directionsIndex][1];
            if(nextrow<0||nextrow>=rows||nextcol<0||nextcol>=cols||visted[nextrow][nextcol]==true)
                directionsIndex=(directionsIndex+1)%4;
            row+=directions[directionsIndex][0];
            col+=directions[directionsIndex][1];
        }
        return order;

    }
}


class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res=new ArrayList<Integer>();
        if(matrix.length==0)
            return res;
        int up=0,down=matrix.length-1,left=0,right=matrix[0].length-1;
        while(true){
            for(int col=left;col<=right;col++)
                res.add(matrix[up][col]);
            if(++up>down) break;
            for(int row=up;row<=down;row++)
                res.add(matrix[row][right]);
            if(--right<left) break;
            for(int col=right;col>=left;col--)
                res.add(matrix[down][col]);
            if(--down<up) break;
            for(int row=down;row>=up;row--)
                res.add(matrix[row][left]);
            if(++left>right) break;
        }
        return res;
    }
}

思考

我做过类似的题目,但是我碰到还是不会,(⊙o⊙)…
评论区大佬真多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值