LeetCode原题54,复习一遍
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> ret = new ArrayList<>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return ret;
int rowstart = 0, rowend = matrix.length-1;
int colstart = 0, colend = matrix[0].length-1;
while(rowstart <= rowend && colstart <= colend){
for(int i = colstart; i <= colend; i++){
ret.add(matrix[rowstart][i]);
}
rowstart++;
if(rowstart > rowend || colstart > colend) break;
for(int i = rowstart; i <= rowend; i++){
ret.add(matrix[i][colend]);
}
colend--;
if(rowstart > rowend || colstart > colend) break;
for(int i = colend; i >= colstart; i--){
ret.add(matrix[rowend][i]);
}
rowend--;
if(rowstart > rowend || colstart > colend) break;
for(int i = rowend; i >= rowstart; i--){
ret.add(matrix[i][colstart]);
}
colstart++;
if(rowstart > rowend || colstart > colend) break;
}
return ret;
}
}