题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
分析
此题其实是一个“剥圈”的题
- 四个点确定一个圈:startRow,startColumn,endRow,endColomn
- startRow和startColumn的初值为0,endRow和endColumn的初值为n-1(注意两者的n不一样)
- 对于一个圈,按照“右下左上”的顺序去剥
- 剥完一个圈之后,更新四个点的位置,继续剥下一个圈
代码
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> printMatrix(int [][] matrix) {
int rowLength = matrix.length;
int columnLength = matrix[0].length;
if(rowLength==0 || columnLength==0){ //只有一行或者一列
return list;
}
int startRow = 0;
int startColumn = 0;
int endRow = rowLength-1;
int endColumn = columnLength-1;
while(startRow<=endRow && startColumn<=endColumn){
printEdge(list, matrix, startRow++, startColumn++, endRow--, endColumn--);
//先调用剥圈函数,再更新四个点的值
}
return list;
}
public void printEdge(ArrayList<Integer> list, int [][] matrix, int startRow, int startColumn, int endRow, int endColumn){
//先处理边界值
if(startRow == endRow){ //只有一行
for(int i=startColumn; i<=endColumn; i++){
list.add(matrix[startRow][i]);
}
}
else if(startColumn == endColumn){//只有一列
for(int j=startRow; j<=endRow; j++){
list.add(matrix[j][startColumn]);
}
}
else{//按照“右,下,左,上”的顺序剥圈
int curColumn = startColumn; //设置一个列指针
int curRow = startRow; //设置一个行指针
while(curColumn != endColumn){ //向右走
list.add(matrix[curRow][curColumn]);
curColumn++;
}
while(curRow != endRow){//向下走
list.add(matrix[curRow][curColumn]);
curRow++;
}
while(curColumn != startColumn){//向左走
list.add(matrix[curRow][curColumn]);
curColumn--;
}
while(curRow != startRow){//向上走
list.add(matrix[curRow][curColumn]);
curRow--;
}
}
}
}