此章节介绍了回环遍历或赋值二位数组的方法,如:
回环遍历的主要思想:
1,每一层的上右下左形成一个环,每一环进行遍历或赋值;
2,增加环的数值/深度,进行逐层遍历,直到遍历到中心数据;
下面是回环赋值的代码,同样可以用于回环遍历;
import org.junit.Test;
@Test
public void test_cycle_print() {
System.out.println("test_cycle_print start");
int[][] array = new int[3][5];
cyclePrint(array,3,5);
printArray(array,3,5);
System.out.println("test_cycle_print end");
}
void cyclePrint(int[][] array, int width, int height) {
// 行列下标index;
int i = 0, j = 0;
// 每一环的计数;
int cycle = 0;
// 赋值的数据,从0开始赋值;
int count = 0;
//4x4,处理2个环形,4x5,也处理2个环形,中间列在while外边特殊处理;
while (width >= (cycle + 1) * 2 && height >= (cycle + 1) * 2) {
//赋值环形上边
j = cycle;
for (i = cycle; i < width - cycle; i++) {
array[i][cycle] = count;
count++;
}
//赋值环形右边
i = width - cycle - 1;
for (j = cycle + 1; j < height - cycle; j++) {
array[i][j] = count;
count++;
}
//赋值环形下边
j = height - cycle - 1;
for (i = width - 1 - cycle - 1; i >= cycle; i--) {
array[i][j] = count;
count++;
}
//赋值环形左边
i = cycle;
for (j = height-1 - cycle - 1; j > cycle; j--) {
array[i][j] = count;
count++;
}
cycle++;
}
//上面4x4可以满足,但是4x3或5x5无法满足对应逻辑,需要特殊处理;
if ((cycle + 1) * 2 - width == 1 && width == height) {
// 1x1,3x3场景;对中间数据进行赋值;
array[cycle][cycle] = count;
} else if ((cycle + 1) * 2 - width == 1) {
// 3x5场景;处理中间一列的数据
i = cycle;
for (j = cycle; j < height - cycle; j++) {
array[i][j] = count;
count++;
}
} else if ((cycle + 1) * 2 - height == 1) {
// 5x3场景;处理中间一行的数据;
j = cycle;
for (i = cycle; i < width - cycle; i++) {
array[i][j] = count;
count++;
}
}
}
// 打印二位数组
void printArray(int[][] array, int width, int height) {
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
}