Description:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
int rows = matrix.length;
if (rows == 0) return list;
int cols = matrix[0].length;
int i = 0;
int j = 0;
while (i < rows && j < cols) {
spiral(list, i, j, rows, cols, matrix);
i++;
j++;
rows--;
cols--;
}
return list;
}
public void spiral(ArrayList<Integer> list, int row, int col, int rows, int cols, int[][] a) {
int i = row;
int j = col;
for ( ; j < cols; j++) list.add(a[i][j]);
j--;
for (i++; i < rows; i++) list.add(a[i][j]);
i--;
for (j--; j >= col && i != row; j--) list.add(a[i][j]);
j++;
for (i--; i > row && j != cols - 1; i--) list.add(a[i][j]);
}
}