您的位置:首页 > Web前端

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

2017-10-04 09:30 351 查看

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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
[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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: