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

19____顺时针打印矩阵

时间:2019-09-04 21:26:31      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:java   pre   ret   top   public   col   结果   思路   遍历   

题目描述:

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

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int rows=matrix.length;   //
        int cols=matrix[0].length;  //
        
        ArrayList<Integer> list=new ArrayList<>(); //要返回的结果
        
        if(rows==0 || cols==0){    //数据有效性检验
            return list;
        }
        
        int left=0;
        int top=0;
        int right=cols-1;
        int bottom=rows-1;    //上下左右
        
        while(left<=right && top<=bottom){
            for(int i=left;i<=right;i++){   //第一行
                list.add(matrix[top][i]);
            }
            
            for(int i=top+1;i<=bottom;i++){   //右边一列
                 list.add(matrix[i][right]);
            }
            
            if(top!=bottom){      //最底一行
                for(int i=right-1;i>=left;i--){
                     list.add(matrix[bottom][i]);
                }
            }
            
             if(left!=right){      //最左一行
                for(int i=bottom-1;i>top;i--){
                     list.add(matrix[i][left]);
                }
            }
            top++;
            left++;
            bottom--;
            right--;
        }
        return list;
    }
}

思路:首先想着顺时针打印一圈的元素,然后采用循环遍历。

19____顺时针打印矩阵

标签:java   pre   ret   top   public   col   结果   思路   遍历   

原文地址:https://www.cnblogs.com/xbfchder/p/11461238.html

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