"Sword Finger Offer" Print Matrix Clockwise (Java)

Title description

Enter a matrix and print each number in turn in a clockwise order from outside to inside. For example, if you enter the following 4 X 4 matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 then print out The numbers 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

AC code

This question is quite similar to an interview question I did before. At that time, I used a very troublesome method when swiping my sword to offer. Now I simplify it. The
printing order is from left to right, from top to bottom. From right to left, from bottom to top, but pay attention to the pit of this question is to consider the case of only one row or one column ~

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
       int rows=matrix.length,cols=matrix[0].length;
        if(rows==0||cols==0)
            return null;
       ArrayList<Integer> res=new ArrayList<>();
       int top=0,bottom=rows-1,left=0,right=cols-1;
       while(left<=right&&top<=bottom){
           for(int i=left;i<=right;i++) {res.add(matrix[top][i]);}
           top++;
           for(int i=top;i<=bottom;i++) {res.add(matrix[i][right]);}
           right--;
           //加判断是为了判别只有一行或者一列的情况。
           if(top<=bottom)
               for(int i=right;i>=left;i--) {res.add(matrix[bottom][i]);}
           bottom--;
           if(left<=right)
               for(int i=bottom;i>=top;i--) {res.add(matrix[i][left]);}
           left++;
       }
       return res;
    }
}
Published 201 original articles · Like9 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/weixin_40992982/article/details/105044617