要求实现:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
例如:如果输入如下矩阵
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。
思路:
矩阵打印都是从外圈到内圈依次打印,假设矩阵是rows行*columns列,我们矩阵的宽度为columns, 高度为rows,我们取左上角开始的坐标为startX, startY,就像剥洋葱一样一圈一圈往里,每次剥掉一圈,矩阵至少会减少两行两列,每剥掉一圈,我们将startX、startY各加1,这样我们可以得出最多可以进行剥掉层次数startX < columns/2; startY < rows/2;
private void printMatrix(int[][] arrayRect, int columns, int rows) {
if (arrayRect == null || columns <= 0 || rows <= 0) {
return;
}
int startX = 0, startY = 0;
int endX = 0, endY = 0;
while(columns > startX * 2 && columns > startY * 2) {
printMatrixCircle(arrayRect, endY, endX, startX, startY);
++startX;
--rows;
--columns;
++startY;
}
}
private void printMatrixCircle(int[][] matrix, int columns, int rows, int startX, int startY) {
for (int i = startX; i < columns; i ++) {
System.out.print(matrix[i][startY]);
}
System.out.println("");
for (int i = startY + 1; i < rows; i ++) {
System.out.print(matrix[columns-1][i]);
}
System.out.println("");
for (int i = columns-2; i >= startX; i--) {
System.out.print(matrix[i][rows-1]);
}
System.out.println("");
for (int i = rows-2; i > startY; i --) {
System.out.print(matrix[startX][i]);
}
System.out.println("");
}