顺时针打印矩阵

来源:互联网 发布:淘宝卖家怎么看总收入 编辑:程序博客网 时间:2024/06/05 00:09

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

IDEA

1.顺时针输出:

top:left2right

right:top2bottom

right:top2bottom

left:bottom2top

2.获得矩阵大小用length

3.将元素加入到ArrayList中用add。

CODE

import java.util.ArrayList;public class Solution {    public ArrayList<Integer> printMatrix(int [][] matrix) {        ArrayList<Integer> res=new ArrayList<Integer> ();        int row=matrix.length;        int col=matrix[0].length;        if(row==0||col==0){            return res;        }        int left=0,right=col-1,top=0,bottom=row-1;        while(left<=right&&top<=bottom){            //top:left2right            for(int i=left;i<=right;i++){res.add(matrix[top][i]);            }            //right:top2bottom            for(int i=top+1;i<=bottom;i++){res.add(matrix[i][right]);            }            if(top!=bottom){                //bottom:right2left                for(int i=right-1;i>=left;i--){res.add(matrix[bottom][i]);            }            }            if(left!=right){                //left:bottom2top                for(int i=bottom-1;i>top;i--){res.add(matrix[i][left]);            }            }            left++;right--;top++;bottom--;        }        return res;    }}



0 0