【考点:规律】顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:
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.
解题思路
如下图所示
设置四个点,分别对应矩形的四个角,然后按照顺时针的顺序输出每一个圈的四条边,循环终止条件是左上角的点坐标不超过矩形中点坐标。
代码提交
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0) return list;
int rowNum = matrix.length;
int colNum = matrix[0].length;
Point leftTopPoint = new Point(0, 0);
Point rightTopPoint = new Point(colNum - 1, 0);
Point leftDownPoint = new Point(0, rowNum - 1);
Point rightDownPoint = new Point(colNum - 1, rowNum - 1);
//循环终止条件
while(leftTopPoint.x * 2 < colNum && leftTopPoint.y * 2 < rowNum) {
//绘制第一行
for(int i = leftTopPoint.x; i <= rightTopPoint.x; i++)
list.add(matrix[leftTopPoint.y][i]);
//绘制第一列
for(int j = rightTopPoint.y + 1; j <= rightDownPoint.y; j++)
list.add(matrix[j][rightTopPoint.x]);
//绘制第二行
for(int k = rightDownPoint.x - 1; k >= leftDownPoint.x; k--)
if(rightDownPoint.y > rightTopPoint.y)//还要检查第二行的纵坐标大于第一行
list.add(matrix[rightDownPoint.y][k]);
//绘制第二列
for(int m = leftDownPoint.y - 1; m > leftTopPoint.y; m--)
if(leftDownPoint.x < rightDownPoint.x)//还要检查第二列横坐标小于第一列
list.add(matrix[m][leftDownPoint.x]);
//左上角
leftTopPoint.x++;
leftTopPoint.y++;
//右上角
rightTopPoint.x--;
rightTopPoint.y++;
//右下角
rightDownPoint.x--;
rightDownPoint.y--;
//左下角
leftDownPoint.x++;
leftDownPoint.y--;
}
return list;
}
private class Point{
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
更多算法解答请点击
《剑指offer》66题JAVA代码算法实现全集
|