顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路
1.左上角的坐标和右下角的坐标固定了一圈矩阵,先打印这一圈矩阵。其中,对矩阵只有一行或者一列分别打印。
2.打印完了这一圈,左上角坐标都+1 ,右下角的都减一,到更内一圈。
比如:5*5的矩阵,(0,0)–(4,4)然后,(1,1)–(3,3)
3.当左上角跑到右下角下面即结束。
注意每一次打印时,最后一个元素不添加,放在下一次循环中添加!!!!!
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list = new ArrayList<>();
int rowi = 0;
int rowl = matrix.length-1;
int coli = 0;
int coll = matrix[0].length-1;
while(rowi <=rowl && coli <= coll){
printCircleArray(list,rowi++,coli++,rowl--,coll--,matrix);
}
return list;
}
public void printCircleArray(ArrayList<Integer> list,int rowTop,int colTop,int rowDown,int colDown,int[][] matrix){
if(rowTop == rowDown){
for(int i = colTop;i <= colDown;i++)
list.add(matrix[rowTop][i]);
}
else if(colTop == colDown){
for(int j = rowTop;j <= rowDown;j++){
list.add(matrix[j][colTop]);
}
}else{
int currentRow = rowTop;
int currentCol = colTop;
while(currentCol < colDown){ //从左到右,注意最后一个不添加,放到下一次循环中
list.add(matrix[currentRow][currentCol++]);
}
while(currentRow < rowDown){//从上到下
list.add(matrix[currentRow++][currentCol]);
}
while(currentCol > colTop){//从右到左
list.add(matrix[currentRow][currentCol--]);
}
while(currentRow > rowTop){
list.add(matrix[currentRow--][currentCol]);
}
}
}
}