问题:
对二维数组进行回形(蛇形)打印
代码:
package com.ziling.mianshi;
/**
* @Author: yipeng
* @Date: 2021/7/27 17:43
*/
public class ArrayBackPrint {
public static void arrayBackPrint(int[][] nums) {
if (nums == null) {
throw new RuntimeException("invalid param");
}
if (nums.length == 0) {
return;
}
int top = 0;
int bottom = nums.length - 1;
int left =0;
int right = nums[0].length - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
System.out.print(nums[top][i] + " ");
}
top++;
if (top > bottom || left > right) {
break;
}
for (int i = top; i <= bottom; i++) {
System.out.print(nums[i][right] + " ");
}
right--;
if (top > bottom || left > right) {
break;
}
for (int i = right; i >= left; i--) {
System.out.print(nums[bottom][i] + " ");
}
bottom--;
if (top > bottom || left > right) {
break;
}
for (int i = bottom; i >= top; i--) {
System.out.print(nums[i][left] + " ");
}
left++;
System.out.println();
}
}
public static void arrayPrint(int[][] nums) {
if (nums == null) {
throw new RuntimeException("invalid param");
}
if (nums.length == 0) {
return;
}
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
public static void arrayInnit(int[][] nums) {
if (nums == null) {
throw new RuntimeException("invalid param");
}
if (nums.length == 0) {
return;
}
int num = 11;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
nums[i][j] = num++;
}
}
}
public static void main(String[] args) {
// int[][] nums = new int[10][7];
int[][] nums = new int[10][10];
arrayInnit(nums);
arrayPrint(nums);
arrayBackPrint(nums);
}
}
Connected to the target VM, address: '127.0.0.1:61385', transport: 'socket'
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
101 102 103 104 105 106 107 108 109 110
11 12 13 14 15 16 17 18 19 20 30 40 50 60 70 80 90 100 110 109 108 107 106 105 104 103 102 101 91 81 71 61 51 41 31 21
22 23 24 25 26 27 28 29 39 49 59 69 79 89 99 98 97 96 95 94 93 92 82 72 62 52 42 32
33 34 35 36 37 38 48 58 68 78 88 87 86 85 84 83 73 63 53 43
44 45 46 47 57 67 77 76 75 74 64 54
55 56 66 65 Disconnected from the target VM, address: '127.0.0.1:61385', transport: 'socket'
Process finished with exit code 0
结论:
定义上下左右对应的坐标值,即可完成整体打印。
注意二维数组长宽不同情况下的下标边界问题判断。

本文介绍了如何对二维数组进行回形(蛇形)打印,通过定义上下左右坐标并处理不同边界条件,实现完整的数组打印。

被折叠的 条评论
为什么被折叠?



