Spiral Matrix
Title: Given a m array elements n (m rows, n columns), follow a helical clockwise order, returns all the elements in the matrix. *
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]
import java.util.ArrayList;
import java.util.List;
public class SpiralOrder {
public static void main(String[] args){
//法① 定义并且初始化二维数组
int[][] a = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
// 法② 定义并且初始化二维数组
// int[][] a = new int[3][3];
// int m = 1;
// for(int i=0 ;i<5;i++){
// for(int j=0;j<5;j++){
// a[i][j]=m;
// m++;
// }
// }
System.out.println(spiralOrder(a));
}
public static List<Integer> spiralOrder(int[][] matrix){
if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
return new ArrayList<>();
List newMatrix = new ArrayList();
int l = 0; //第一列
int r = matrix[0].length-1; //列数
int u = 0; //第一行
int d = matrix.length-1; //行数
while(l <= r && u <= d) {
//上方一行
for(int i= l; i <= r ; i++){
newMatrix.add(matrix[u][i]);
}
u++;
//右边一列
for(int i = u;i <= d;i++){
newMatrix.add(matrix[i][r]);
}
r--;
//下面一行
for(int i = r;i >= l && u<= d;i--){
newMatrix.add(matrix[d][i]);
}
d--;
//左边一列
for(int i = d;i >=u && l<= r;i--){
newMatrix.add(matrix[i][l]);
}
l++;
}
return newMatrix;
}
}
operation result:
[1, 2, 3, 6, 9, 8, 7, 4, 5]