LeetCode 54 (Spiral Matrix)Java

原题:Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

旋转打印矩阵;

思路:我采取的是循环,应该考虑递归实现会清晰一些,之后考虑递归;

去除特殊情况:

最后一行是奇数应该怎么输出;

代码:

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> resList=new ArrayList<Integer>();
        int rows=matrix.length;
        if(rows==0){
            return resList;
        }
        int cols=matrix[0].length;
        if(rows==1 && cols==1){
            resList.add(matrix[0][0]);
            return resList;
        }
        int times=0;
        int min=rows>cols?cols:rows;
        while(min>0){
            if(rows-1-times==times){
                for(int i=times;i<cols-times;i++){
                    resList.add(matrix[times][i]);
                }
                break;
            }
            if(cols-1-times==times){
                for(int j=times;j<rows-times;j++){
                    resList.add(matrix[j][cols-1-times]);
                }
                break;
            }
            for(int i=times;i<cols-1-times;i++){
                resList.add(matrix[times][i]);
            }
            for(int j=times;j<rows-1-times;j++){
                resList.add(matrix[j][cols-1-times]);
            }
            for(int i=cols-1-times;i>times;i--){
                resList.add(matrix[rows-1-times][i]);
            }  
            for(int j=rows-1-times;j>times;j--){
                resList.add(matrix[j][times]);
            } 
            times++;
            min-=2;
        }
        return resList;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值