题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
import java.util.*; import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { int startRows = 0; int startCols = 0; int endRows = matrix.length - 1; int endCols = matrix[0].length - 1; ArrayList<Integer> list = new ArrayList<>(); while (startRows <= endRows && startCols <= endCols) { if (startRows == endRows) { for (int i = startCols; i <= endCols; i++) { list.add(matrix[startRows][i]); } break; } if (startCols == endCols) { for (int i = startRows; i <= endRows; i++) { list.add(matrix[i][startCols]); } break; } for (int i = startCols; i <= endCols - 1; i++) { list.add(matrix[startRows][i]); } for (int i = startRows; i <= endRows - 1; i++) { list.add(matrix[i][endCols]); } for (int i = endCols; i >= startCols + 1; i--) { list.add(matrix[endRows][i]); } for (int i = endRows; i >= startRows + 1; i--) { list.add(matrix[i][startCols]); } startRows++; endRows--; startCols++; endCols--; } return list; } }