题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (matrix.length == 0) {
return null;
}
int rows = matrix.length;
int cols = matrix[0].length;
int pos = 0; // 0/1/2/3 四个方向
int colLeft = 0, colRight = cols - 1;
int rowTop = 0, rowBottom = rows - 1;
int i = 0, j = 0;
// 重点是循环条件控制好、设置字段标记遍历方向
while (colLeft <= colRight && rowTop <= rowBottom) {
switch (pos) {
case 0:
list.add(matrix[i][j]);
if (j == colRight) {
pos = 1;
rowTop = ++i;
} else {
j++;
}
break;
case 1:
list.add(matrix[i][j]);
if (i == rowBottom) {
pos = 2;
colRight = --j;
} else {
i++;
}
break;
case 2:
list.add(matrix[i][j]);
if (j == colLeft) {
pos = 3;
rowBottom = --i;
} else {
j--;
}
break;
case 3:
list.add(matrix[i][j]);
if (i == rowTop) {
pos = 0;
colLeft = ++j;
} else {
i--;
}
}
}
return list;
}
}