顺时针打印矩阵

2018/10/20 Offer 共 724 字,约 3 分钟

title

problem link

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

solution

import java.util.*;
public class Solution {
    public ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> res=new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return res;
        int n=matrix.length;
        int m=matrix[0].length;
        int r1=0,r2=n-1;
        int c1=0,c2=m-1;
        while (r1<=r2&&c1<=c2){
            for(int i=c1;i<=c2;i++){
                res.add(matrix[r1][i]);
            }
            for(int i=r1+1;i<=r2;i++){
                res.add(matrix[i][c2]);
            }
            if(r2>r1){
                for(int i=c2-1;i>=c1;i--){
                    res.add(matrix[r2][i]);
                }
            }
            if(c2>c1){
                for(int i=r2-1;i>r1;i--){
                   res.add(matrix[i][c1]);
                }
            }
            r1++;
            r2--;
            c1++;
            c2--;
        }
        return res;
    }
}

Search

    Table of Contents