顺时针打印矩阵

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

解题思路:一次去掉一个外圈,当最后只剩一行或一列时停止递归。(ps:这题就是绕,仔细点就解决了!!!)

 1 import java.util.ArrayList;
 2 public class Solution {
 3     public ArrayList<Integer> printMatrix(int [][] matrix) {
 4         ArrayList arr = new ArrayList();
 5         if(matrix==null||matrix.length==0){
 6             return arr;
 7         }else{
 8             way_getArr(matrix,0,matrix[0].length-1,0,matrix.length-1,arr);
 9             return arr;
10         }
11     }
12     public void way_getArr(int[][] matrix,int left,int right,int top,int bottom,ArrayList<Integer> arr){
13         if(left<right&&top<bottom){
14             for(int i=left;i<=right;i++){
15             arr.add(matrix[top][i]);
16             }
17             for(int j=top+1;j<=bottom;j++){
18                 arr.add(matrix[j][right]);
19             }
20             for(int k=right-1;k>=left;k--){
21                 arr.add(matrix[bottom][k]);
22             }
23             for(int l=bottom-1;l>top;l--){
24                 arr.add(matrix[l][left]);
25             }
26             way_getArr(matrix,left+1,right-1,top+1,bottom-1,arr);
27         }else if(left==right&&top<bottom){
28             for(int i=top;i<=bottom;i++){arr.add(matrix[i][left]);}
29         }else if(top==bottom&&left<right){
30             for(int i=left;i<=right;i++){arr.add(matrix[top][i]);}
31         }else if(left==right&&top==bottom){
32             arr.add(matrix[top][left]);
33         }else{}
34     }
35 }

打卡!!!

fighting💪

posted @ 2020-01-10 23:27  hu啦啦啦  阅读(110)  评论(0编辑  收藏  举报