lpy1990

# Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all
elements of the matrix in spiral order.

Example 1:

Input:
[ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]
Output:
[1,2,3,6,9,8,7,4,5] Example 2:

Input: [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12] ]
Output:
[1,2,3,4,8,12,11,10,9,5,6,7]

## 代码

``````class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix.length == 0) {
return res;
}
int m = matrix.length;
int n = matrix[0].length;
int mid = Math.min(m, n)/2;
for (int i = 0; i < mid; i++) {
//向右
for (int j = i; j < n - i - 1; j++) {
}
//向下
for (int j = i; j < m - i -1; j++) {
}
//向左
for (int j = n - i - 1; j > i; j--) {
}
//向上
for (int j = m - i -1; j > i; j--) {
}
}
//如果多一行或者一列
if (Math.min(m, n)%2 == 1) {
if (m < n){//添加中间一行
for (int j = mid; j < n -mid; j++) {
}
} else {//添加中间一列
for (int j = mid; j < m - mid; j++) {
}
}
}
return res;
}
}``````

# 59. Spiral Matrix II

``````Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
``````

## 复杂度

``````class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
if (n == 0) {
return res;
}
int mid = n/2;
int k = 1;
for (int i = 0; i < mid; i++) {
for (int j = i; j < n -i - 1; j++) {//向右
res[i][j] = k++;
}
for (int j = i; j < n - i - 1; j++) {//向下
res[j][n-i-1] = k++;
}
for (int j = n - i - 1; j>i ; j--) { //向左
res[n-i-1][j] = k++;
}
for (int j = n - i -1; j> i;j--) { //向上
res[j][i] = k++;
}
}
if (n%2 == 1) {
res[mid][mid] = k;
}
return res;

}
}``````

26 声望
10 粉丝
0 条评论