题目:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
public static ArrayList<Integer> printMatrix(int[][] matrix) {
if (matrix.length == 0) {
return null;
}
ArrayList<Integer> list = new ArrayList<>();
if (matrix.length == 1) {
for (int i = 0; i < matrix[0].length; i++) {
list.add(matrix[0][i]);
}
return list;
}
if (matrix[0].length == 1) {
for (int i = 0; i < matrix.length; i++) {
list.add(matrix[i][0]);
}
return list;
}
int[][] map = new int[matrix.length + 2][matrix[0].length + 2];
//初始化地图
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (i == 0 || j == 0 || i == map.length - 1 || j == map[0].length - 1) {
map[i][j] = 1;
} else {
map[i][j] = 0;
}
}
}
for (int i = 1; i < map.length - 1; ) {
for (int j = 1; j < map[0].length - 1; ) {
if (map[i][j] == 0) {
list.add(matrix[i - 1][j - 1]);
map[i][j] = 1;
}
//如果右边有
if (map[i][j + 1] == 0 && map[i - 1][j] == 1) {
j++;
continue;
}
//下边有
if (map[i + 1][j] == 0) {
i++;
continue;
}
//左边
if (map[i][j - 1] == 0) {
j--;
continue;
}
if (map[i - 1][j] == 0) {
i--;
continue;
}
if (map[i + 1][j] == 1 && map[i][j + 1] == 1 && map[i - 1][j] == 1 && map[i][j - 1] == 1) {
break;
}
}
break;
}
return list;
}