題目
用螺旋的方式打印矩陣, 比如如下的矩陣
0 1 2 3
4 5 6 7
8 9 10 11
打印順序爲: 0 1 2 3 7 11 10 9 8 4 5 6
實現
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = in.nextInt();
}
}
f(matrix);
}
public static void f(int[][] m) {
//用兩個點a和b,分別表示左上角的點和右下角的點,來控制轉圈的打印順序
int ah = 0;
int al = 0;
int bh = m.length - 1;
int bl = m[0].length - 1;
while (ah <= bh && al <= bl) { //注意這裏的條件,第二個條件不能少,比如說五行四列的情況
printEdge(m, ah++, al++, bh--, bl--);
}
}
public static void printEdge(int[][] m , int ah, int al, int bh, int bl) {
//考慮只有一行的情況
if (ah == bh) {
while (al <= bl) {
System.out.print(m[ah][al++] + " ");
}
} else if (al == bl) { //考慮只有一列的情況下
while (ah <= bh) {
System.out.print(m[ah++][al] + " ");
}
} else { //正常情況下
int curC = al;
int curR = ah;
//打印上面的行
while (curC < bl) {
System.out.print(m[curR][curC++] + " ");
}
//打印右面的列
while (curR < bh) {
System.out.print(m[curR++][curC] + " ");
}
//打印下面的行
while (curC > al) {
System.out.print(m[curR][curC--] + " ");
}
//打印左邊的列
while (curR > ah) {
System.out.print(m[curR--][curC] + " ");
}
}
}
}