题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
分析:剑指offer原题,这里留个记录方便以后查看
import java.util.ArrayList;
class Solution {
public ArrayList<Integer> printMatrix(int[][] matrix) {
int row = matrix.length;
int line = matrix[0].length;
//创建缓存数组
ArrayList<Integer> al = new ArrayList<Integer>();
//如果矩阵为空,直接返回
if (matrix == null | row == 0 | line == 0)
return null;
//初始化四个方向的值
int left = 0, top = 0, right = line - 1, bottom = row - 1;
//在收缩为1点前
while (left <= right & top <= bottom) {
//从左至右
for (int i = left; i <= right; ++i)
al.add(matrix[top][i]);
//从上+1到下
for (int i = top + 1; i <= bottom; ++i) {
al.add(matrix[i][right]);
}
//如果上不等于下
if (top != bottom)
//则从右-1到左
for (int i = right - 1; i >= left; --i) {
al.add(matrix[bottom][i]);
}
//如果左不等于右
if (left != right)
//则从下-1到上(不包括上,因为第一个从左至右已经包括了)
for (int i = bottom - 1; i > top; --i) {
al.add(matrix[i][left]);
}
//缩圈
left++;
top++;
right--;
bottom--;
}
return al;
}
}