原题:Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
旋转打印矩阵;
思路:我采取的是循环,应该考虑递归实现会清晰一些,之后考虑递归;
去除特殊情况:
最后一行是奇数应该怎么输出;
代码:
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> resList=new ArrayList<Integer>();
int rows=matrix.length;
if(rows==0){
return resList;
}
int cols=matrix[0].length;
if(rows==1 && cols==1){
resList.add(matrix[0][0]);
return resList;
}
int times=0;
int min=rows>cols?cols:rows;
while(min>0){
if(rows-1-times==times){
for(int i=times;i<cols-times;i++){
resList.add(matrix[times][i]);
}
break;
}
if(cols-1-times==times){
for(int j=times;j<rows-times;j++){
resList.add(matrix[j][cols-1-times]);
}
break;
}
for(int i=times;i<cols-1-times;i++){
resList.add(matrix[times][i]);
}
for(int j=times;j<rows-1-times;j++){
resList.add(matrix[j][cols-1-times]);
}
for(int i=cols-1-times;i>times;i--){
resList.add(matrix[rows-1-times][i]);
}
for(int j=rows-1-times;j>times;j--){
resList.add(matrix[j][times]);
}
times++;
min-=2;
}
return resList;
}
}