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

来源:互联网 发布:Ai人工智能武汉 编辑:程序博客网 时间:2024/06/07 01:00

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

<分析>
每次打印完一个外圈,就四个角都往内部进一位,即左上,右上,左下,右下

需要注意的就是打印  下  左两个for循环,要注意单行和单列的情况,加一个if判断就ok了

import java.util.ArrayList;/** *  * @author zy * @date 2017年10月3日 下午8:33:31 * @Decription 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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. */public class Ex12 {public ArrayList<Integer> printMatrix(int[][] matrix) {ArrayList<Integer> result = new ArrayList<>();int high = matrix.length;int len = matrix[0].length;if (high == 0) {return result;}int left = 0,top = 0,right = len - 1,bottom = high - 1;while(left<=right && top<=bottom){//打印上for(int i = left;i<=right;i++){result.add(matrix[top][i]);}//打印右for(int j = top+1;j<=bottom;j++){result.add(matrix[j][right]);}//打印下//要防止出现单行if(top!=bottom){for(int k = right-1;k >=left;k-- ){result.add(matrix[bottom][k]);}}//打印左//要防止出现单列if (left!=right) {for(int n = bottom -1;n>=top+1;n--){result.add(matrix[n][left]);}}left++;top++;right--;bottom--;}return result;}public static void main(String[] args) {Ex12 mEx12 = new Ex12();int[][] mx= new int[2][2];mx[0][0] = 1;mx[0][1] = 2;mx[1][1] = 4;mx[1][0] = 3;ArrayList<Integer> arrayList = new ArrayList<>();arrayList = mEx12.printMatrix(mx);System.out.println(arrayList);}}


原创粉丝点击