这个题目主要是进行多圈循环,从外向内,一层一层输出。定义 left right top bottom 四个变量,每循环一圈,则四个变量先给你缩一位。这题的难点是单行或者单列的输出。因此在从右向左和从下向上的时候给出条件限制,避免重复打印。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer> ();
int row = matrix.length;
int col = matrix[0].length;
int left =0 , top = 0, right = col - 1,bottom = row - 1;
if (row == 0 || col == 0) return result;
while(left <= right && top <= bottom){
for(int i = left ;i<= right;i++ ){
result.add(matrix[top][i]);
}
for(int i = top+1 ;i<= bottom;i++ ){
result.add(matrix[i][right]);
}
for(int i = right - 1 ;i>= left && top<bottom;i-- ){ // top<bottom避免在一行的情况下还进行输出。
result.add(matrix[bottom][i]);
}
for(int i = bottom - 1 ;i>= top+1 && left<right;i-- ){ // left<right避免在一列的情况下,还进行打印
result.add(matrix[i][left]);
}
top++; left++; right--; bottom--;
}
return result;
}
}