题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
import java.util.*; import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return new ArrayList<>(); } List<Integer> list = new ArrayList<>(matrix.length * matrix[0].length); // 最左 最右 最上 最下 int a = -1, b = matrix[0].length, c = -1, d = matrix.length; // 右1 下2 左3 上4 int dir = 1; while (list.size() < matrix.length * matrix[0].length) { if (dir == 1 && list.size() < matrix.length * matrix[0].length) { c ++; for (int i = a + 1; i <= b - 1; i ++) { list.add(matrix[c][i]); } dir = 2; } if (dir == 2 && list.size() < matrix.length * matrix[0].length) { b --; for (int i = c + 1; i <= d - 1; i ++) { list.add(matrix[i][b]); } dir = 3; } if (dir == 3 && list.size() < matrix.length * matrix[0].length) { d --; for (int i = b - 1; i >= a + 1; i --) { list.add(matrix[d][i]); } dir = 4; } if (dir == 4 && list.size() < matrix.length * matrix[0].length) { a ++; for (int i = d - 1; i >= c + 1; i --) { list.add(matrix[i][a]); } dir = 1; } } return (ArrayList<Integer>) list; } }