java语言实现二维数组的顺时针、逆时针的遍历
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/400e5a5a47d7a6441cd621c825dc718d.png#pic_center)
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
print(matrix);
}
private static void print(int[][] matrix) {
int leftUpRow = 0;
int leftUpCol = 0;
int rightDownRow = matrix.length-1;
int rightDownCol = matrix[0].length-1;
while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol){
int r = leftUpRow;
int c = leftUpCol;
while (r <= rightDownRow){
System.out.print(matrix[r++][c] + " ");
}
r = rightDownRow;
c++;
while (c <= rightDownCol){
System.out.print(matrix[r][c++] + " ");
}
c = rightDownCol;
r--;
while (r >= leftUpRow){
System.out.print(matrix[r--][c] + " ");
}
r = leftUpRow;
c--;
while (c > leftUpCol){
System.out.print(matrix[r][c--] + " ");
}
leftUpCol++;
leftUpRow++;
rightDownCol--;
rightDownRow--;
}
}
}
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
print(matrix);
}
private static void print(int[][] matrix) {
int leftUpRow = 0;
int leftUpCol = 0;
int rightDownRow = matrix.length-1;
int rightDownCol = matrix[0].length-1;
while (leftUpRow <= rightDownRow && leftUpCol <= rightDownCol){
int r = leftUpRow;
int c = leftUpCol;
while (c <= rightDownCol){
System.out.print(matrix[r][c++] + " ");
}
c = rightDownRow;
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] + " ");
}
leftUpCol++;
leftUpRow++;
rightDownCol--;
rightDownRow--;
}
}
}