Java算法–第四章–多维数组和矩阵(1)顺时针打印二维数组
代码:
package matrix;
public class Print20Arr {
public static void main(String[] args) {
int[][] matrix = { { 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 } };
print(matrix);
}
static void print(int[][] matrix) {
int r = 0, leftUpRow = 0;
int c = 0, leftUpCol = 0;
int rightDownRow = matrix.length - 1;
int rightDownCol = matrix[0].length - 1;
while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol) {
// 上面一行
while (c <= rightDownCol) {
System.out.print(matrix[r][c++] + " ");
}
// 恢复
c = rightDownCol;
r++;
// 右边一列
while (r <= rightDownRow) {
System.out.print(matrix[r++][c] + " ");
}
// 恢复
r = rightDownRow;
c--;
// 下面一边
while (c >= leftUpCol) {
System.out.print(matrix[r][c--] + " ");
}
// 恢复
c = leftUpCol;
r--;
while (r > leftUpRow) {
System.out.print(matrix[r--][c] + " ");
}
leftUpRow++;
leftUpCol++;
rightDownRow--;
rightDownCol--;
c = leftUpCol;
r = leftUpRow;
}
}
}
输出:
1 2 3 4 5 10 15 20 25 24 23 22 21 16 11 6 7 8 9 14 19 18 17 12 13
版权声明:本文为wp_886原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。