Topic describes
// You are given a matrix with m rows and n columns. Please return all elements of the matrix in clockwise spiral order.Copy the code
Answer key
// // : 0 ms, beat 100.00% of all Java submissions // memory consumption: Class Solution {public List<Integer> spiralOrder(int[][] matrix) {int row1 = 0; int row2 = matrix.length - 1; int col1 = 0; int col2 = matrix[0].length - 1; List<Integer> res = new ArrayList<>(); while (row1 <= row2 && col1 <= col2) { printMatrix(matrix, row1, row2, col1, col2, res); row1++; row2--; col1++; col2--; } return res; } public void printMatrix(int[][] matrix, int row1, int row2, int col1, int col2, List<Integer> res) { for (int i = col1; i <= col2; i++) { res.add(matrix[row1][i]); } for (int i = row1 + 1; i <= row2; i++) { res.add(matrix[i][col2]); } for (int i = col2 - 1; i >= col1; i--) { res.add(matrix[row2][i]); } for (int i = row2 - 1; i >= row1 + 1 ; i--) { res.add(matrix[i][col1]); }}}Copy the code