顺时针打印二维矩阵

 

 

 


public ArrayList printMatrix(int[][] matrix) {
ArrayList result = new ArrayList();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return result;
}
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
while (true) {
//上边界
for (int col = left; col <= right; col++) {
result.add(matrix[top][col]);
}
top++;
if (top > bottom) break;

//右边界
for (int row = top; row <= bottom; row++) {
result.add(matrix[row][right]);
}
right--;
if (left > right) break;

//下边界
for (int col = right; col >= left; col--) {
result.add(matrix[bottom][col]);
}
bottom--;
if (top > bottom) break;

//左边界
for (int row = bottom; row >= top; row--) {
result.add(matrix[row][left]);
}
left++;
if (left > right) break;
}
return result;
}
 

 

posted @ 2022-01-19 08:58  daniel456  阅读(49)  评论(0编辑  收藏  举报