同事说最近螺旋矩阵挺火,笔者简单试了试,实现以下算法。
int[][] array = {
{1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}
};
image.png
如上图,需要遍历这种特殊的二维数组。我们可以看出遍历的顺序是从左到右,再从上到下,再从右到左,再从下到上,然后一直循环。我们这里还有4个标记,一个是从上到下当前行的标记,从下到上行的标记,从左到右从右到左的二个列的标记,当循环遍历的时候,这4个标记逐渐向中间靠拢,直到重合循环结束。
以上算法不只是适用于方阵,也适用于行数和列数不一样的任何矩阵。Java实现的算法如下:
int[][] array = {
{1, 2, 3, 4, 5, 6},
{18, 19, 20, 21, 22, 7},
{17, 28, 29, 30, 23, 8},
{16, 27, 26, 25, 24, 9},
{15, 14, 13, 12, 11, 10}
};
int row = 5;
int column = 6;
//四个标记
int rowFromTop = 0;
int rowFromBottom = row - 1;
int columnFromRight = column - 1;
int columnFromLeft = 0;
int index = 0;
//遍历的方向,初始是向右方向
String direction = "右";
for (int i = 0; i < row * column; i++) {
if (direction.equals("右")) {
System.out.println(array[rowFromTop][index]);
index++;
if (index > columnFromRight) {
direction = "下";
rowFromTop++;
index = rowFromTop;
}
} else if (direction.equals("下")) {
System.out.println(array[index][columnFromRight]);
index++;
if (index > rowFromBottom) {
direction = "左";
columnFromRight--;
index = columnFromRight;
}
} else if (direction.equals("左")) {
System.out.println(array[rowFromBottom][index]);
index--;
if (index < columnFromLeft) {
direction = "上";
rowFromBottom--;
index = rowFromBottom;
}
} else if (direction.equals("上")) {
System.out.println(array[index][columnFromLeft]);
index--;
if (index < rowFromTop) {
direction = "右";
columnFromLeft++;
index = columnFromLeft;
}
}
}
网友评论