码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer:顺时针打印矩阵

时间:2020-01-29 15:50:05      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:span   描述   void   --   res   list   col   stat   输入   

一、题目描述

  输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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

 

二、代码

public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
       ArrayList<Integer> res = new ArrayList<>();
        if(matrix.length==0||matrix[0].length==0){
            return res;
        }
        int sR = 0;
        int sC = 0;
        int eR = matrix.length-1;
        int eC = matrix[0].length-1;
        
        while(sR<=eR&&sC<=eC){
            printEdge(matrix, sR++, sC++, eR--, eC--, res);
        }
        return res;
    }
    
    //打印一圈
    public static void printEdge(int[][] matrix,int sR,int sC,int eR,int eC,ArrayList<Integer> res){
        if(sR==eR){
            for(int i=sC;i<=eC;i++){
                res.add(matrix[sR][i]);
            }
        }else if(sC==eC){
            for(int i=sR;i<=eR;i++){
                res.add(matrix[i][sC]);
            }
        }else{
            int curSR = sR;
            int curSC = sC;
            
            //向右
            while(curSC!=eC){
                res.add(matrix[sR][curSC]);
                curSC++;
            }
            
            //向下
            while(curSR!=eR){
                res.add(matrix[curSR][eC]);
                curSR++;
            }
            
            //向左
            while(curSC!=sC){
                res.add(matrix[eR][curSC]);
                curSC--;
            }
            
            //向上
            while(curSR!=sR){
                res.add(matrix[curSR][sC]);
                curSR--;
            }
        }
            
    }
}

 

  

剑指offer:顺时针打印矩阵

标签:span   描述   void   --   res   list   col   stat   输入   

原文地址:https://www.cnblogs.com/blzm742624643/p/12240363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!