二维数组顺时针遍历
1、题目要求
From PDD
-
给你一个
m*n的二维数组arr[][],按照顺时针遍历输出 -
比如下面的数组,其输出顺序应该为 1~15
int[][] arr = new int[][]{ {1, 2, 3, 4, 5}, {12, 13, 14, 15, 6}, {11, 10, 9, 8, 7}, };
2、代码思路
这道题并不难,使用两个变量 row 和 col 分别作为行、列指针,使用两个变量 xLeft 和 xRight 维护左右边界,使用两个变量 yUp 和 yDown 维护上下边界,使用一个变量 direction 维护当前遍历的方向
3、代码实现
-
代码
/** * @ClassName ArrayClockwiseIter * @Description TODO * @Author Heygo * @Date 2020/8/16 12:43 * @Version 1.0 */ public class ArrayClockwiseIter { public static void main(String[] args) { int[][] arr = new int[][]{ {1, 2, 3, 4, 5}, {12, 13, 14, 15, 6}, {11, 10, 9, 8, 7}, }; clockwiseIter(arr); } /** * 顺时针遍历输出二维数组 * @param arr 待遍历输出的二维数组 */ public static void clockwiseIter(int[][] arr) { // 行、列指针 int row = 0; int col = 0; // 列的左右边界 int xLeft = 0; int xRight = arr[0].length - 1; // 行的上下边界 int yUp = 0; int yDown = arr.length - 1; // 已遍历输出的元素个数 int count = 0; int totalCount = arr.length * arr[0].length; // 行走方向:0 表示从左往右,1 表示从上往下,2 表示从右往左,3 表示从下往下 int direction = 0; while (count < totalCount) { if (direction == 0) { for (col = xLeft; col <= xRight; col++, count++) { System.out.print(arr[row][col]+" "); } System.out.println(); yUp += 1; // 上边界 direction = 1; // 变换方向 col--; } else if (direction == 1) { for (row = yUp; row <= yDown; row++, count++) { System.out.print(arr[row][col]+" "); } System.out.println(); xRight -= 1; // 右边界 direction = 2; // 变换方向 row--; } else if (direction == 2) { for (col = xRight; col >= xLeft; col--, count++) { System.out.print(arr[row][col]+" "); } System.out.println(); yDown -= 1; // 下边界 direction = 3; // 变换方向 col++; } else if (direction == 3) { for (row = yDown; row >= yUp; row--, count++) { System.out.print(arr[row][col]+" "); } System.out.println(); xLeft += 1; // 左边界 direction = 0; // 变换方向 row++; } } } } -
程序运行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

584

被折叠的 条评论
为什么被折叠?



