顺时针打印矩阵JAVA
时间: 2023-08-29 13:07:07 浏览: 107
顺时针打印矩阵.md
好的,我可以回答您的问题。顺时针打印矩阵的JAVA代码如下:
```java
public class PrintMatrixInCircle {
public static void printMatrixInCircle(int[][] matrix) {
if (matrix == null) {
return;
}
int rows = matrix.length;
int cols = matrix[0].length;
int start = 0;
while (cols > start * 2 && rows > start * 2) {
printMatrixInCircleCore(matrix, rows, cols, start);
start++;
}
}
public static void printMatrixInCircleCore(int[][] matrix, int rows, int cols, int start) {
int endX = cols - 1 - start;
int endY = rows - 1 - start;
// 从左到右打印一行
for (int i = start; i <= endX; i++) {
System.out.print(matrix[start][i] + " ");
}
// 从上到下打印一列
if (start < endY) {
for (int i = start + 1; i <= endY; i++) {
System.out.print(matrix[i][endX] + " ");
}
}
// 从右到左打印一行
if (start < endY && start < endX) {
for (int i = endX - 1; i >= start; i--) {
System.out.print(matrix[endY][i] + " ");
}
}
// 从下到上打印一列
if (start < endY - 1 && start < endX) {
for (int i = endY - 1; i > start; i--) {
System.out.print(matrix[i][start] + " ");
}
}
}
public static void main(String[] args) {
int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printMatrixInCircle(matrix);
}
}
```
希望能够帮助您!如果您还有其他问题需要帮助,请随时提出。
阅读全文