剑指offer_顺时针打印矩阵

2020-02-13  本文已影响0人  彼得朱

1、题目

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

2、思路

3、代码

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
       ArrayList<Integer> array = new ArrayList<Integer>();
        int i_min = 0;
        int i_max = matrix.length-1;
        int j_min = 0;
        int j_max = matrix[0].length-1;
        int count = 0;
        int all = (i_max+1)*(j_max+1);
        while(true){
            if(count==all) break;
            // 遍历圈的上面部分
            for(int j = j_min;j<=j_max;j++){
                array.add(matrix[i_min][j]);
                count++;
            }
            i_min++;
            if(count==all) break;
            // 遍历圈的右侧部分
            for(int i = i_min;i<=i_max;i++){
                array.add(matrix[i][j_max]);
                count++;
            }
            if(count==all) break;
            j_max--;
            // 遍历圈的下面部分
            for(int j=j_max;j>=j_min;j--){
                 array.add(matrix[i_max][j]);
                 count++;
            }
            if(count==all) break;
            i_max--;
            // 遍历圈的左面部分
            for(int i=i_max;i>=i_min;i--){
                 array.add(matrix[i][j_min]);
                 count++;
            }
            j_min++;    
        }
        return array;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读