Sword to Offer-29 顺时针打印矩阵 ❀
in Algorithm
题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。例如:如果输入如下
4 X 4矩阵:12345678910111213141516, 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。
解题思路:
1、用四个指针记录下目前还未遍历的最大最小行数列数;
未被遍历的最小行数大于最大行数,或者最小列数大于最大列数的时候,终止循环;
(即,循环条件为同时满足两组min<=max)
2、每一次循环转一个环形读取数据,需注意边界的取值:
(1)向右→的遍历可从min遍历到max,向下↓的遍历可从min+1遍历到max,向左←的遍历可以从max-1遍历到min,向上↑的遍历可以从max-1遍历到min+1;
(2)每完成一次环状遍历后,缩小范围,min值+1,max值-1。
问题图解:
AC代码:
// Print Maxtrix's Elements Clockwise
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
//用于返回的ArrayList
ArrayList<Integer> ret = new ArrayList<>();
int rowMin = 0, rowMax = matrix.length - 1;
int colMin = 0, colMax = matrix[0].length - 1;
while (rowMin<=rowMax && colMin<=colMax) {
for (int i=colMin; i<=colMax; i++) {
ret.add(matrix[rowMin][i]);
}
for (int i=rowMin+1; i<=rowMax; i++) {
ret.add(matrix[i][colMax]);
}
if (rowMin != rowMax) {
for (int i=colMax-1; i>=colMin; i--) {
ret.add(matrix[rowMax][i]);
}
}
if (colMin != colMax) {
for (int i=rowMax-1; i>rowMin; i--) {
ret.add(matrix[i][colMin]);
}
}
rowMin++;
rowMax--;
colMin++;
colMax--;
}
return ret;
}
}
补充说明:
- 这里是牛客编码链接