输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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) {
int row=matrix.length;
int col=matrix[0].length;
ArrayList<Integer> list=new ArrayList<>();
if (row==0||col==0)
return list;
int left=0,right=col-1,top=0,bottom=row-1;
while((left<=right)&&(top<=bottom))
{
if(top==bottom)//只有一行时
{
for(int i=left;i<=right;i++)
{
list.add(matrix[top][i]);
}
}
else if(left==right)//只有一列时
{
for(int i=top;i<=bottom;i++)
{
list.add(matrix[i][left]);
}
}
else{
int tmpRow=top;
int tmpCol=left;
while(tmpCol<right)//从左往右打印
{
list.add(matrix[top][tmpCol]);
tmpCol++;
}
while(tmpRow<bottom)//从上往下打印
{
list.add(matrix[tmpRow][right]);
tmpRow++;
}
while(tmpCol>left)//从右往左打印
{
list.add(matrix[bottom][tmpCol]);
tmpCol--;
}
while(tmpRow>top)//从下往上打印
{
list.add(matrix[tmpRow][left]);
tmpRow--;
}
}
left++;
top++;
right--;
bottom--;
}
return list;
}
}