这道题在好几次的笔试中都见到了,整理一下。
将顺时针打印的数组一个圈一个圈的看,
每个圈有四种情况:
最多的包括从左到右-从上到下-从右到左-从下到上(行>=3,列>=2)
①
其次的包括从左到右-从上到下-从右到左(行>=2,列>=2)
②
接着是从左到右-从上到下(行>=2,列>=1)
③
最后是从左到右(行>=1,列>=1)
④
实现代码:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();// 数组行
int m = scanner.nextInt();// 数组列
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {// 输入数组
for (int j = 0; j < m; j++) {
arr[i][j] = scanner.nextInt();
}
}
print(arr, n, m);// 打印
}
public static void print(int[][]arr, int n, int m) {
int start_row = 0, start_cos = 0;
int end_row = n - 1, end_cos = m - 1;
// 占据的行数,比如:第三行到第一行,3-1+1=3,占据3行,比如第三行,3-3+1=1,占据1行
int row = end_row - start_row + 1;
// 占据的列数,与行数同理
int cos = end_cos - start_cos + 1;
while (row >=1 && cos >= 1) {
if (row >= 3 && cos >= 2) {// 情况①
for (int i = start_cos; i <= end_cos; i++) {
System.out.print(arr[start_row][i] + " ");
}
for (int i = start_row + 1; i <= end_row; i++) {
System.out.print(arr[i][end_cos] + " ");
}
for (int i = end_cos - 1; i >= start_cos; i--) {
System.out.print(arr[end_row][i] + " ");
}
for (int i = end_row - 1; i > start_row; i--) {
System.out.print(arr[i][start_cos] + " ");
}
} else if (row >= 2 && cos >= 2) {// 情况②
for (int i = start_cos; i <= end_cos; i++) {
System.out.print(arr[start_row][i] + " ");
}
for (int i = start_row + 1; i <= end_row; i++) {
System.out.print(arr[i][end_cos] + " ");
}
for (int i = end_cos - 1; i >= start_cos; i--) {
System.out.print(arr[end_row][i] + " ");
}
} else if (row >= 2 && cos >= 1) {// 情况③
for (int i = start_cos; i <= end_cos; i++) {
System.out.print(arr[start_row][i] + " ");
}
for (int i = start_row + 1; i <= end_row; i++) {
System.out.print(arr[i][end_cos] + " ");
}
} else {// 情况④
for (int i = start_cos; i <= end_cos; i++) {
System.out.print(arr[start_row][i] + " ");
}
}
// 往内缩
start_row++;
start_cos++;
end_row--;
end_cos--;
// 重新计算行数和列数
row = end_row - start_row + 1;
cos = end_cos - start_cos + 1;
}
}
打印