题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路
本题算法没有难度,但是需要写出一个容易理解的形式。
定义矩阵左上角(rS, cS)和右下角(rE,cE)的坐标,然后围绕坐标定义的外围依次打印即可,打印完让左上角坐标往右下方向移一位,右下角坐标往左上方向移一位,定义新的外围,不断循环直至终止。
注意一行和一列的特殊情况。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int[][] matrix) {
int rS = 0;
int cS = 0;
int rE = matrix.length - 1;
int cE = matrix[0].length - 1;
ArrayList<Integer> ans = new ArrayList();
while (rS <= rE && cS <= cE) {
if (rS == rE) {
//一行
for (int i = cS; i <= cE; i++) {
ans.add(matrix[rS][i]);
}
} else if (cS == cE) {
//一列
for (int i = rS; i <= rE; i++) {
ans.add(matrix[i][cS]);
}
} else {
//一般情况
int curC = cS;
int curR = rS;
while (curC != cE) {
ans.add(matrix[rS][curC]);
curC++;
}
while (curR != rE) {
ans.add(matrix[curR][cE]);
curR++;
}
while (curC != cS) {
ans.add(matrix[rE][curC]);
curC--;
}
while (curR != rS) {
ans.add(matrix[curR][cS]);
curR--;
}
}
rS++;
cS++;
rE--;
cE--;
}
return ans;
}
}