順時針打印矩陣(順時針螺旋打印二維數組)

題目描述
輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下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) {
        ArrayList<Integer> arr=new ArrayList<Integer>();
        int rs=0,re=matrix.length-1;
        int cs=0,ce=matrix[0].length-1;
        int x,y;
        while(rs<re&&cs<ce){
            x=rs;
            y=cs;
            while(y<=ce){
                arr.add(matrix[x][y]);
                y++;
            }
            y--;
            x++;
            while(x<=re){
                arr.add(matrix[x][y]);
                x++;
            }
            x--;
            y--;
            while(y>=cs){
                arr.add(matrix[x][y]);
                y--;
            }
            y++;
            x--;
            while(x>rs){
                arr.add(matrix[x][y]);
                x--;
            }
            rs++;
            re--;
            cs++;
            ce--;
        }
        if(rs==re){
            for(int i=cs;i<=ce;i++) arr.add(matrix[rs][i]);
        }
        else if(cs==ce){
            for(int i=rs;i<=re;i++) arr.add(matrix[i][cs]);
        }
        return arr;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章