题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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、数组内总元素数量与list大小一致时,表示数组遍历完成。
3、及时调整上下左右四个边界。
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> list =new ArrayList<>(); //左右两个列边界 int left = 0,right = matrix[0].length-1; //上下两个行边界 int top = 0,bottom = matrix.length - 1; //数组中元素数量 int count = matrix.length * matrix[0].length; //结束条件,所有元素已添加到列表中 while(list.size() != count){ //往右遍历 int pos = left; while(pos<=right){ list.add(matrix[top][pos]); pos++; } //所有元素已添加到列表中,跳出循环 if(list.size() == count){ break; } //当前最上面一行已遍历完,调整上边界。 top++; //往下遍历 pos = top; while(pos<=bottom){ list.add(matrix[pos][right]); pos++; } if(list.size() == count){ break; } //当前最右列已遍历完,调整右边界 right--; //往左遍历 pos = right; while(pos >= left){ list.add(matrix[bottom][pos]); pos--; } if(list.size() == count){ break; } bottom--; //网上遍历 pos = bottom; while(pos >= top){ list.add(matrix[pos][left]); pos--; } if(list.size() == count){ break; } //不要忘记,调整左边界 left++; } return list; } }