Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
-
1234567891011121314151617181920212223242526272829303132333435363738public List<Integer> (int[][] matrix) {List<Integer> list = new LinkedList<>();if (matrix.length == 0 || matrix[0].length == 0) {return list;}int n = matrix.length;int m = matrix[0].length;int c = (Math.min(m, n) + 1) / 2;for (int i = 0; i < c; i++) {int lastRow = n - 1 - i;int lastCol = m - 1 - i;if (lastRow == i) {for (int j = i; j <= lastCol; j++) {list.add(matrix[i][j]);}} else if (lastCol == i) {for (int j = i; j <= lastRow; j++) {list.add(matrix[j][i]);}} else {for (int j = i; j < lastCol; j++) {list.add(matrix[i][j]);}for (int j = i; j < lastRow; j++) {list.add(matrix[j][lastCol]);}for (int j = lastCol; j > i; j--) {list.add(matrix[lastRow][j]);}for (int j = lastRow; j > i; j--) {list.add(matrix[j][i]);}}}return list;}
近期评论