顺时针打印矩阵
本题将一个4*4的矩阵顺时针打印出来,我们可以先打印矩阵最外圈的数(1,2,3,4,8,12,16,,15,14,13,9,5),再打印矩阵内圈的数(6,7,11,10)。
public ArrayList<Integer> printMatrix(int [][] matrix) { int tR = 0; int tC = 0; int dR = matrix.length - 1; int dC = matrix[0].length - 1; ArrayList<Integer> list = new ArrayList<Integer>(); //判断是否满足打印的要求 while (tR <= dR && tC <= dC) { //打印的矩阵只有一行 if (tR == dR) { for (int i = tC; i <= dC; i++) { list.add(matrix[tR][i]); } // 打印的矩阵只有一列 } else if (tC == dC){ for (int i = tR; i <= dR; i++) { list.add(matrix[i][tC]); } //打印的矩阵为4*4的矩阵 } else { int curR = tR; int curC = tC; while (curC != dC) { list.add(matrix[tR][curC]); curC++; } while (curR != dR) { list.add(matrix[curR][dC]); curR++; } while (curC != tC) { list.add(matrix[dR][curC]); curC--; } while (curR != tR) { list.add(matrix[curR][tC]); curR--; } } // 进行下一轮的打印 tR++; tC++; dR--; dC--; } return list; }