题目
用螺旋的方式打印矩阵, 比如如下的矩阵
0 1 2 3
4 5 6 7
8 9 10 11
打印顺序为: 0 1 2 3 7 11 10 9 8 4 5 6
思路
1.定义两个点分别指向矩阵左上角和右下角两个位置。
2.根据p1,p2的行和列的值将一圈分成4块,按顺序打印这4部分的值。
3.一圈打印结束后向右下角移动p1,向左上角移动p2。
4.重复2,3步骤,直到p1,p2相遇。(注意当p1,p2在同一行和同一列的时候需要单独讨论,这个时候只要单独打印一行或者一列)
图解
代码实现
public class Problem03_SpiralMatrix {
public static void spiralMatrix(int[][] matrix) {
//1.首先定义两个点p1,p2位置表示为matrix[r1][c1],matrix[r2][c2]
//分别指向矩阵左上角和右下角两个位置
int r1 = 0;
int c1 = 0;
int r2 = matrix.length - 1;
int c2 = matrix[0].length - 1;
//2.当r1 <= r2 && c1 <= c2打印结束
while (r1 <= r2 && c1 <= c2) {
//3.调用打印方法,一圈打印结束后向右下角移动p1,向左上角移动p2
printEdge(matrix, r1++, c1++, r2--, c2--);
}
}
public static void printEdge(int[][] matrix, int r1, int c1, int r2, int c2) {
int tempC = c1;
int tempR = r1;
if (r1 == r2) { //在同一行
while (tempC <= c2) {
System.out.print(matrix[tempR][tempC] + " ");
tempC++;
}
} else if (c1 == c2) { //在同一列
while (tempR <= r2) {
System.out.print(matrix[tempR][tempC] + " ");
tempR++;
}
} else { //按顺序打印四个部分的数
while (c2 - tempC > 0) {
System.out.print(matrix[tempR][tempC] + " ");
tempC++;
}
while (r2 - tempR > 0) {
System.out.print(matrix[tempR][tempC] + " ");
tempR++;
}
while (tempC > c1) {
System.out.print(matrix[tempR][tempC] + " ");
tempC--;
}
while (tempR > r1) {
System.out.print(matrix[tempR][tempC] + " ");
tempR--;
}
}
}
//测试代码
public static void main(String[] args) {
int[][] matrix = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
spiralMatrix(matrix);
}
}