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].
Spiral Matrix I思路
- 规律是先向右,再向下,再向左,再向上搜索,搜索的时候从matrix中取出对应位置的数放到result中,每次搜索完都需要更新rowStart || rowEnd || colStart || colEnd
- 终止条件是:rowStart > rowEnd || colStart > colEnd
Example
rowStart->1 2 3 4
5 6 7 8
rowEnd-> 9 10 11 12
| |
colStart colEnd
打印顺序:1234, 8 12, 11 10 9, 5, 6 7
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0) {
return result;
}
int rowStart = 0;
int rowEnd = matrix.length - 1;
int colStart = 0;
int colEnd = matrix[0].length - 1;
//终止条件是:rowStart > rowEnd || colStart > colEnd
// 规律是先向右,再向下,再向左,再向上搜索,每次搜索完都需要更新rowStart || rowEnd || col Start|| colEnd
while (true) {
//->right
for (int i = colStart; i <= colEnd; i++) {
result.add(matrix[rowStart][i]);
}
rowStart++;
if (rowStart > rowEnd) break;
//->down
for (int i = rowStart; i <= rowEnd; i++) {
result.add(matrix[i][colEnd]);
}
colEnd--;
if (colStart > colEnd) break;
//->left
for (int i = colEnd; i >= colStart; i--) {
result.add(matrix[rowEnd][i]);
}
rowEnd--;
if (rowStart > rowEnd) break;
//->up
for (int i = rowEnd; i >= rowStart; i--) {
result.add(matrix[i][colStart]);
}
colStart++;
if (colStart > colEnd) break;
}
return result;
}
}
Spiral Matrix ii
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
Example
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路
- 与Spiral Matrix I正好相反,需要根据矩阵大小创建这个数组。同样可以用1中的规律来创建这个数组
- 先创建一个int[n][n]大小的Matrix,因为matrix填充的数是1 - n^2,所以根据1中的规律,先向右,再向下,再向左,再向上搜索,搜索的时候将matrix中对应位置填充为cur(cur从1开始,每次填充一个数cur ++),每次搜索完都需要更新rowStart || rowEnd || colStart || colEnd
- 终止条件是:rowStart > rowEnd || colStart > colEnd
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
if (n <= 0) {
return result;
}
int rowStart = 0;
int rowEnd = n - 1;
int colStart = 0;
int colEnd = n - 1;
int cur = 1;
while (true) {
for (int i = colStart; i <= colEnd; i++) {
result[rowStart][i] = cur;
cur++;
}
rowStart++;
if (rowStart > rowEnd) break;
for (int i = rowStart; i <= rowEnd; i++) {
result[i][colEnd] = cur;
cur++;
}
colEnd--;
if (colStart > colEnd) break;
for (int i = colEnd; i >= colStart; i--) {
result[rowEnd][i] = cur;
cur++;
}
rowEnd--;
if (rowStart > rowEnd) break;
for (int i = rowEnd; i >= rowStart; i--) {
result[i][colStart] = cur;
cur++;
}
colStart++;
if (colStart > colEnd) break;
}
return result;
}
}