1.题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 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.
2.解题思路
打印分为四步:循环的次数即打印的圈速,即
rows>start*2&&column>start*2
(1) 从左到右打印一行:
开始于[start,start],结束于[start,col-start-1]
(2) 从上到下打印一行,
开始于[start+1,col-start-1],结束于[col-start-1,col-start-1]
(3) 从右到左打印一行
开始于[col-start-1,col-start-2],结束于[col-start-1,start]
(4) 从下到上打印一行
开始于[col-start-2,start],结束于[start+1,start]
3.代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { int rows = matrix.length; int columns = matrix[0].length; ArrayList<Integer> list = new ArrayList<Integer>();
int start = 0; while (rows > start * 2 && columns > start * 2){ int endRow = rows - 1 - start; int endColumn = columns - 1 - start;
for (int i = start; i <= endColumn; i++) list.add(matrix[start][i]); if (endRow > start){ for (int i = start + 1; i <= endRow; i++) list.add(matrix[i][endColumn]); } if (endRow > start && endColumn > start){ for (int i = endColumn - 1; i >= start; i--) list.add(matrix[endRow][i]); }
if (endRow >= start + 2 && endColumn > start){ for (int i = endRow - 1; i > start; i--) list.add(matrix[i][start]); } start++; } return list; } }
|