zoukankan      html  css  js  c++  java
  • 19.顺时针打印矩阵

    题目描述:

      输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

    思路分析:

      设置startrow和startcol,对应矩阵的左上角。设置endrow和endcol对应矩阵的右下角,然后从左上角开始进行一周的遍历,然后startrow和startcol,endrow ,endcol沿着对角线靠近。再进行一周的遍历。

    代码:

    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> printMatrix(int [][] matrix) {
            ArrayList<Integer>res=new ArrayList<>();
            if(matrix==null||matrix.length==0)
                return res;
            return help(matrix,0,0,matrix.length-1,matrix[0].length-1,res);
        }
        public ArrayList<Integer>help(int [][]matrix,int startrow,int startcol,int endrow,int endcol,ArrayList<Integer>res){
            if(startrow<endrow&&startcol<endcol){
                for(int j=startcol;j<=endcol;j++){
                    res.add(matrix[startrow][j]);
                }
                for(int i=startrow+1;i<=endrow;i++){
                    res.add(matrix[i][endcol]);
                }
                for(int j=endcol-1;j>=startcol;j--){
                    res.add(matrix[endrow][j]);
                }
                for(int i=endrow-1;i>startrow;i--){
                    res.add(matrix[i][startcol]);
                }
                return help(matrix,startrow+1,startcol+1,endrow-1,endcol-1,res);
            }
            else if(startrow==endrow&&startcol<endcol){
                for(int j=startcol;j<=endcol;j++)
                    res.add(matrix[startrow][j]);
            }else if(startcol==endcol&&startrow<endrow){
                for(int i=startrow;i<=endrow;i++)
                    res.add(matrix[i][startcol]);
            }else if(startcol==endcol&&startrow==endrow){
                res.add(matrix[startrow][startcol]);
            }
            return res;
        }
    }
    
  • 相关阅读:
    Excel Add-in
    并发控制MsSql
    Kaggle实战分类问题2
    NuGet
    Pomelo分布式游戏服务器框架
    Ambari
    oracle 多行转多列查询
    Oauth2.0 用Spring-security-oauth2
    bug排查小结
    Linux之lsof命令
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10720519.html
Copyright © 2011-2022 走看看