题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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<>();
int up = 0;
int down = matrix.length;
int left = 0;
int right = matrix[0].length;
int curNum = 0;
int totalNum = down * right;
if (down == 0 && right == 0) {
return list;
}
while (curNum < totalNum) {
//向右
for (int i = left; i < right; i++) {
list.add(matrix[up][i]);
curNum++;
}
up++;
if (curNum == totalNum) {
break;
}
//向下
for (int i = up; i < down; i++) {
list.add(matrix[i][right - 1]);
curNum++;
}
right--;
if (curNum == totalNum) {
break;
}
//向左
for (int i = right - 1; i >= left; i--) {
list.add(matrix[down - 1][i]);
curNum++;
}
down--;
if (curNum == totalNum) {
break;
}
//向上
for (int i = down - 1; i >= up; i--) {
list.add(matrix[i][left]);
curNum++;
}
left++;
}
return list;
}
}