题目:
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
解题思路:
当遍历元素时,当下一个元素超出行数,或者超出列数,或者行数小于0,列数小于0,以及元素被标识了,说明方向要改变了
题解:
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
List<Integer> merge = merge(matrix);
System.err.println(merge);
}
public static List<Integer> merge(int[][] matrix) {
//存储结果
List<Integer> result = new LinkedList<>();
//行的长度
int rowLength = matrix.length;
//列的长度
int colLength = matrix[0].length;
//标识元素
boolean[][] booleans = new boolean[rowLength][colLength];
//用于标识方向,分别是向右,向下,向左,向上
int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
//计算出总元素的数量
int totals = rowLength * colLength;
//标识方向的下标,当下标为0就是向右,1就是向下,2向左,3向上
int directionIndex = 0;
//当前行数
int row = 0;
//当前列数
int col = 0;
for (int i = 1; i <= totals; i++) {
//将元素加入集合
result.add(matrix[row][col]);
//标识这个元素已经被遍历了
booleans[row][col] = true;
//以原方向,计算下一个行数,和和下一个列数
int nextRow = row + direction[directionIndex][0];
int nextCol = col + direction[directionIndex][1];
//如果超过列数,或者超过行数,或者行数小于0,列数小于0,或者已经被遍历了,说明要改变方向了,
//每四次一个循环,所以用%4,计算方向
if (nextRow > rowLength - 1 || nextCol > colLength - 1 || nextCol < 0 || nextRow < 0 || booleans[nextRow][nextCol]) {
directionIndex = (directionIndex + 1) % 4;
}
//改变方向后,计算出行数,和列数
row = row + direction[directionIndex][0];
col = col + direction[directionIndex][1];
}
return result;
}