題目
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]
.
這題沒用到什麼特別的技巧,就是一層一層來,需要注意一些邊界條件。
代碼
import java.util.ArrayList; public class SpiralMatrix { public ArrayListspiralOrder(int[][] matrix) { ArrayList list = new ArrayList (); if (matrix == null || matrix.length == 0) { return list; } int minRow = 0; int minColumn = 0; int maxRow = matrix.length - 1; int maxColumn = matrix[0].length - 1; while (minRow <= maxRow && minColumn <= maxColumn) { for (int i = minColumn; i <= maxColumn; ++i) { list.add(matrix[minRow][i]); } for (int i = minRow + 1; i <= maxRow; ++i) { list.add(matrix[i][maxColumn]); } if (minRow != maxRow) { for (int i = maxColumn - 1; i >= minColumn; --i) { list.add(matrix[maxRow][i]); } } if (minColumn != maxColumn) { for (int i = maxRow - 1; i > minRow; --i) { list.add(matrix[i][minColumn]); } } ++minRow; ++minColumn; --maxRow; --maxColumn; } return list; } }