📅  最后修改于: 2023-12-03 15:25:46.414000             🧑  作者: Mango
这是一个可以打印矩阵边界元素的Java程序。矩阵是一个由m行n列组成的二维数组。为了方便打印,我们规定第一个元素为矩阵左上角,m × n个元素依次排列。
public class MatrixBoundaryPrinter {
public void printBoundaryElements(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
if (rows == 1) { // 矩阵只有1行
for (int j = 0; j < cols; j++) {
System.out.print(matrix[0][j] + " ");
}
} else if (cols == 1) { // 矩阵只有1列
for (int i = 0; i < rows; i++) {
System.out.print(matrix[i][0] + " ");
}
} else { // 正常情况
// 打印第一行
for (int j = 0; j < cols; j++) {
System.out.print(matrix[0][j] + " ");
}
// 打印最后一列
for (int i = 1; i < rows; i++) {
System.out.print(matrix[i][cols-1] + " ");
}
// 打印最后一行
for (int j = cols - 2; j >= 0; j--) {
System.out.print(matrix[rows-1][j] + " ");
}
// 打印第一列
for (int i = rows - 2; i >= 1; i--) {
System.out.print(matrix[i][0] + " ");
}
}
System.out.println();
}
}
代码说明:
使用示例:
public class Main {
public static void main(String[] args) {
int[][] matrix = new int[][]{
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}};
MatrixBoundaryPrinter printer = new MatrixBoundaryPrinter();
printer.printBoundaryElements(matrix);
}
}
输出结果:
1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6
Markdown代码片段:
```java
public class MatrixBoundaryPrinter {
public void printBoundaryElements(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
if (rows == 1) { // 矩阵只有1行
for (int j = 0; j < cols; j++) {
System.out.print(matrix[0][j] + " ");
}
} else if (cols == 1) { // 矩阵只有1列
for (int i = 0; i < rows; i++) {
System.out.print(matrix[i][0] + " ");
}
} else { // 正常情况
// 打印第一行
for (int j = 0; j < cols; j++) {
System.out.print(matrix[0][j] + " ");
}
// 打印最后一列
for (int i = 1; i < rows; i++) {
System.out.print(matrix[i][cols-1] + " ");
}
// 打印最后一行
for (int j = cols - 2; j >= 0; j--) {
System.out.print(matrix[rows-1][j] + " ");
}
// 打印第一列
for (int i = rows - 2; i >= 1; i--) {
System.out.print(matrix[i][0] + " ");
}
}
System.out.println();
}
}