顺时针打印矩阵,首先要确定循环终止的条件,就是top=bottom, left=right
先从左到右打印第一行,再从上到下打印最后一列,接着从右到左打印最后一行,最后从下到上打印第一列。执行完一次循环之后,top++;right–;bottom–;left++。进行判断left和right,top和bottom,如果不相等继续循环打印。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
if(row == 0 || col == 0)
return null;
ArrayList<Integer> list = new ArrayList<Integer>();
int left = 0, top = 0, bottom = row-1, right = col-1;
while(top<=bottom && left<=right){
for(int i=left;i<=right;i++){
list.add(matrix[top][i]);
}
for(int j=top+1;j<=bottom;j++){
list.add(matrix[j][right]);
}
if(top != bottom){
for(int t=right-1;t>=left;t--){
list.add(matrix[bottom][t]);
}
}
if(left != right){
for(int k=bottom-1;k>top;k--){
list.add(matrix[k][left]);
}
}
top++;left++;right--;bottom--;
}
return list;
}
}