顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
思路
- 整体是按着一圈一圈打印,需要找到循环继续的条件:columns > startX * 2并且rows > startY * 2
- 注意打印每圈的时候,四个边的打印循环起始条件
代码
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
if (matrix == null) {
return null;
}
ArrayList<Integer> list = new ArrayList<Integer>();
int rows = matrix.length;
int columns = matrix[0].length;
int start = 0;
while (rows > start * 2 && columns > start * 2) {
int endX = columns - 1 - start;
int endY = rows - 1 - start;
for (int i = start; i <= endX; i++) {
list.add(matrix[start][i]);
}
if (start < endY) {
for (int i = start + 1; i <= endY; i++) {
list.add(matrix[i][endX]);
}
}
if (start < endX && start < endY) {
for (int i = endX - 1; i >= start; i--) {
list.add(matrix[endY][i]);
}
}
if (start < endX && start < endY - 1) {
for (int i = endY - 1; i >= start + 1; i--) {
list.add(matrix[i][start]);
}
}
start++;
}
return list;
}
}
时间: 2024-12-11 06:13:36