美文网首页
剑指offer----顺时针打印矩阵

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

作者: qming_c | 来源:发表于2018-02-04 19:26 被阅读0次

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

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

    相关文章

      网友评论

          本文标题:剑指offer----顺时针打印矩阵

          本文链接:https://www.haomeiwen.com/subject/dkfvzxtx.html