题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
解题思路:
大家都知道一个矩阵只需要知道左上角和右下角坐标就可以得到它的大小,所以首先取矩阵的左上角和右下角坐标分别记为:
int x_top = 0;int y_top = 0;
int x_bottom = row - 1;int y_bottom = col - 1;//row为矩阵行,col为矩阵列
整个过程可分为:从左到右打印数组、从上到下打印、从右到左、从下到上。通过上述四个位置变量来控制打印,没打印一圈,x_top++;y_top++;x_bottom–;y_bottom–;意思就是往矩阵中心缩进一步,当两个坐标点重合时,即到最后一个数字,遍历结束。
private static ArrayList<Integer> pMatrix(int[][] matrix) {
int col = matrix[0].length;// 列数
int row = matrix.length;// 行数
ArrayList<Integer> resultList = new ArrayList<>();
if(col == 0 || row == 0){
return resultList;
}
int x_top = 0;int y_top = 0;//矩阵左上点和右下点
int x_bottom = row - 1;int y_bottom = col - 1;
while(x_top <= x_bottom && y_top <= y_bottom){
//左边到右边=>行不变,列变
for(int i = y_top;i <= y_bottom;i++) resultList.add(matrix[x_top][i]);
//上到下=>列不变,行变
for(int i = x_top + 1;i <= x_bottom;i++) resultList.add(matrix[i][y_bottom]);
//右到左=>行不变,列变
if (x_top != x_bottom)
{
for(int i = y_bottom - 1; i >= y_top; --i)
resultList.add(matrix[x_bottom][i]);
}
//下到上=>列不变,行变
if(y_top != y_bottom)
{
for(int i = x_bottom - 1; i > x_top; --i)
resultList.add(matrix[i][y_top]);
}
x_top++;y_top++;x_bottom--;y_bottom--;
}
return resultList;
}