题目
思路及代码
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList <Integer> result = new ArrayList<>();
if(matrix == null || matrix.length == 0|| matrix[0].length == 0)
return result;
int left =0;
int up = 0;
int down = matrix.length-1;
int right = matrix[0].length-1;
while(true){
//向右打印
for(int i = left;i<= right;i++){
result.add(matrix[up][i]);
}
up++;
if(up > down) break;
//向下打印
for(int j= up;j<= down;j++){
result.add(matrix[j][right]);
}
right --;
if(left > right) break;
//向左打印
for(int i = right;i>= left;i--){
result.add(matrix[down][i]);
}
down --;
//向上打印
if(up > down) break;
for(int j = down;j >= up;j--){
result.add(matrix[j][left]);
}
left++;
if(left > right) break;
}
return result;
}
}