递归,读完一行,将该行删去,将矩阵左旋90度。重复操作。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(matrix.length==0)
return list;
luoxuan(matrix,list);
return list;
}
//矩阵左旋
public int[][] reverseMatrix(int[][] matrix){
int[][] newarr = new int[matrix[0].length][matrix.length];
for(int i = 0;i<matrix.length;i++){
for(int j = 0;j<matrix[i].length;j++){
newarr[matrix[i].length-1-j][i] = matrix[i][j];
}
}
return newarr;
}
public void luoxuan(int[][] matrix ,ArrayList<Integer> list){
for(int i = 0; i<matrix[0].length;i++){
list.add(matrix[0][i]);
}
if(matrix.length == 1){
return;
}
int[][] newarr = new int[matrix.length-1][matrix[0].length];
for(int i = 1;i<matrix.length;i++){
for(int j = 0;j<matrix[i].length;j++){
newarr[i-1][j] = matrix[i][j];
}
}
newarr = reverseMatrix(newarr);
luoxuan(newarr,list);
}
}