剑指offer----顺时针打印矩阵

2018-02-04  本文已影响0人  qming_c

题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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> array = new ArrayList<Integer>();
        if(matrix.length == 0){
            return null;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int top = 0, bottom = row - 1, left = 0, right = col -1;
        while((top <= bottom) && (left <= right)){
            for(int i = left ; i <= right; i++){
                array.add(matrix[top][i]);
            }
            top++;
            for(int i = top; i <= bottom; i++){
                array.add(matrix[i][right]);
            }
            right--;
            if(top <= bottom){
                for(int i = right; i >= left; i--){
                array.add(matrix[bottom][i]);
                }
                bottom--;
            }
            
            if(left <= right){
                for(int i = bottom; i >= top; i--){
                    array.add(matrix[i][left]);
                }
                left++;
            }
           
        }
        return array;
    }
}

大致的思路就是使用四个数值分别表示遍历过后各个方向的位置,后面的两个判断条件要谨记,因为有可能前面的操作的进行之后竖向或者横向的元素已经遍历过了。

上一篇下一篇

猜你喜欢

热点阅读