题目
给定一个整型矩阵matrix,请按照转圈的方式打印它。要求额外空间复杂度为O(1)。
例如:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
打印结果为1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12
思路
题意为从左上角(a,b)开始转圈打印矩阵
这道题我们只需要考虑重要的几个边界即可。首先根据左上角(a,b)和右下角(c,d)确定这个矩阵,以顶点(x,y)开始沿着打印路线开始移动打印,开始(x,y)向右移动(x++)
,当到达右边界d时向下移动(y++)
,到达下边界c时向左移动(x--)
,到达左边界b时向上移动(y++)
,以此类推
代码
/**
* 转圈打印矩阵
* 【题目】 给定一个整型矩阵matrix,请按照转圈的方式打印它。
* 例如:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
* 打印结果为:1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12
* 【要求】 额外空间复杂度为O(1)。
*
* @Author: FangJu
* @Date: 2019/8/11
*/
public class PrintMatrixSpiralOrder {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
spiralOrderPrint(matrix);
}
/**
* 转圈打印矩阵
*
* @param matrix 矩阵
*/
private static void spiralOrderPrint(int[][] matrix) {
int a = 0;
int b = 0;
int c = matrix.length - 1;
int d = matrix[0].length - 1;
while (a <= c && b <= d) {
printEdge(matrix, a++, b++, c--, d--);
}
}
/**
* 顺时针旋转打印
* (a,b)左上角坐标
* (c,d)右下角坐标
*
* @param matrix 矩阵
* @param a 矩阵左上角行
* @param b 矩阵左上角列
* @param c 矩阵右下角行
* @param d 矩阵右下角列
*/
private static void printEdge(int[][] matrix, int a, int b, int c, int d) {
if (a == c) {//只有一行
while (b <= d) {
System.out.print(matrix[a][b++] + "\t");
}
} else if (b == d) {//只有一列
while (a <= c) {
System.out.print(matrix[a++][b] + "\t");
}
} else {
int x = b;
int y = a;
while (x < d) {
System.out.print(matrix[a][x++] + "\t");
}
while (y < c) {
System.out.print(matrix[y++][d] + "\t");
}
while (x > b) {
System.out.print(matrix[c][x--] + "\t");
}
while (y > a) {
System.out.print(matrix[y--][b] + "\t");
}
}
}
}