码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer19

时间:2018-01-19 14:05:21      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:数据   ==   arrays   nbsp   new   情况   amp   offer   lis   

package jianzhiOffer; import java.util.ArrayList; import java.util.Arrays; /**  * 输入一个矩阵,按照从外向里以顺时针的顺序依  * 次打印出每一个数字,例如,如果输入如下矩阵:   * 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.  * @author user  * 思想,用左上和右下的坐标定位出一次要旋转打印  * 的数据,一次旋转打印结束后,往对角分别前进和  * 后退一个单位。提交代码时,主要的问题出在没有  * 控制好后两个for循环,需要加入条件判断,防止  * 出现单行或者单列的情况。  */ public class ch19 { public static ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> arr = new ArrayList<>();        int rows = matrix.length;        int cols = matrix[0].length;        //如果输入了一个空的矩阵        if(rows == 0 || cols == 0) {         return null;        }        //坐标的定义        int top = 0,left = 0,bottom = rows - 1,right = cols - 1;    while(top <= bottom && left <= right) {        //从左往右        for (int i = left; i <= right; i++) arr.add(matrix[top][i]);        //从上往下        for (int j = top + 1; j <= bottom; j++) arr.add(matrix[j][right]);        //从右往左        if(top != bottom)         for (int k = right - 1; k >= left; k--) arr.add(matrix[bottom][k]);        //从下往上        if(left != right)          for (int l = bottom - 1; l > top; l--) arr.add(matrix[l][left]);        top++;left++;bottom--;right--;        }    return arr;     } }


剑指offer19

标签:数据   ==   arrays   nbsp   new   情况   amp   offer   lis   

原文地址:http://blog.51cto.com/12222886/2062800

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!