首页 > 其他 > 详细

剑指offer:顺时针打印矩阵

时间:2020-04-16 01:32:42      阅读:71      评论:0      收藏: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.

解题思路

使用循环,从最外层开始遍历,左——》右,上——》下,右——》左,下——》上。遍历时将元素放入List。

遍历完最外层,继续遍历倒数第二层。

注意对角线的元素,不要重复添加到List中。

	public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> list = new ArrayList<>();
    	int height = matrix.length;
        int width = matrix[0].length;
        if(width == 0 && height == 0) return list;
        int top = 0;
        int bottom = height - 1;
        int left = 0;
        int right = width - 1;
        while(top<=bottom && left <=right){		
            for(int i=left;i<=right;i++){	//顶端从左到右
                list.add(matrix[top][i]);
            }
            for(int i=top+1;i<=bottom;i++){	//右边从上到下
                list.add(matrix[i][right]);
            }
            if(top != bottom){
                for(int i=right-1;i>=left;i--){	//底端从右到左
                    list.add(matrix[bottom][i]);
                }
            }
            if(left != right){
                for(int i=bottom-1;i>top;i--){	//左端从下到上
                    list.add(matrix[i][left]);
                }
            }
            top++;bottom--;left++;right--;	//向内递减
        }
    	return list;
    }

剑指offer:顺时针打印矩阵

原文:https://www.cnblogs.com/le-le/p/12709642.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!