java逆时针打印矩阵
时间: 2023-05-26 20:07:12 浏览: 38

顺时针打印矩阵.md
以下是Java代码,逆时针打印一个矩阵:
```
public static void printMatrixInReverse(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return;
int rows = matrix.length;
int cols = matrix[0].length;
int left = 0, top = 0, right = cols - 1, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][left] + " ");
}
left++;
for (int j = left; j <= right; j++) {
System.out.print(matrix[bottom][j] + " ");
}
bottom--;
if (left <= right && top <= bottom) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][right] + " ");
}
right--;
}
if (left <= right && top <= bottom) {
for (int j = right; j >= left; j--) {
System.out.print(matrix[top][j] + " ");
}
top++;
}
}
}
```
例如,给定以下矩阵:
```
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
```
打印结果将为:9 8 7 6 5 4 3 2 1
阅读全文
相关推荐













