《剑指offer》NO29 顺时针打印矩阵 详解 <Java实现>
程序员文章站
2022-03-20 23:28:03
public ArrayList printMatrix(int[][] matrix) { ArrayList res = new ArrayList<>(); //定义行与列的做大最小值 int r1 = 0, r2 = matrix.length - 1; int c1 = 0, c2 = matrix[0].length - 1; ......
public ArrayList<Integer> printMatrix(int[][] matrix)
{
ArrayList<Integer> res = new ArrayList<>();
//定义行与列的做大最小值
int r1 = 0, r2 = matrix.length - 1;
int c1 = 0, c2 = matrix[0].length - 1;
while (r1 < r2 && c1 < c2)
{
//1.从左到右
//第一步,从左往右打印
for (int i = c1; i < c2; i ++)
{
res.add(matrix[r1][i]);
}
//上边界向内收缩
r1++;
//第二步判断边界是否相遇
if (r1 > r2)
break;
//2.从上到下
//第一步从上到下打印
for (int i = r1; i <= r2; i++)
{
res.add(matrix[i][c2]);
}
//右边界向内收缩
c2--;
//第二步判断边界是否相遇
if (c1 > c2)
break;
//3.从右到左
//第一步从右到左打印一列
for (int i = c2; i >= c1; i-- )
{
res.add(matrix[r2][i]);
}
//下边界向内收缩
r2--;
//第二步判断边界是否相遇
if (r1 > r2)
break;
//4.从下到上
//第一步从下到上打印
for (int i = r2; i >= r1; i--)
{
res.add(matrix[i][c1]);
}
//左边界向右收缩
c1++;
//第二步判断边界条件
if (c1 > c2)
break;
}
return res;
}
本文地址:https://blog.csdn.net/qq_46190347/article/details/110878854