题目描述
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例1

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
题目分析
模拟.
使用 directions 表示不同方向对应的位移,按 右、下、左、上 的顺序排列,使用 index 表示当前方向,则 (index + 1) % 4 为下一个方向。
使用 visit 数组对访问过的位置做标记,按照当前方向不断移动,如果失败则换到下一个方向。
当 ans 里的数量和数字总数相同时,遍历结束。
Java
public List<Integer> spiralOrder(int[][] matrix) {
int[][] directions = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int index = 0;
int m = matrix.length;
int n = matrix[0].length;
boolean[][] visit = new boolean[m][n];
List<Integer> ans = new ArrayList<>();
int i = 0, j = -1;
while (ans.size() < m * n) {
int nextI = i + directions[index][0];
int nextJ = j + directions[index][1];
if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && !visit[nextI][nextJ]) {
i = nextI;
j = nextJ;
ans.add(matrix[i][j]);
visit[i][j] = true;
} else {
index = (index + 1) % 4;
}
}
return ans;
}
Kotlin
fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val ans = mutableListOf<Int>()
val m = matrix.size
val n = matrix[0].size
val directions = listOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0))
val visit = Array(m) { BooleanArray(n) }
var index = 0
var i = 0
var j = -1
while (ans.size < m * n) {
val nextI = i + directions[index][0]
val nextJ = j + directions[index][1]
if (nextI in 0 until m && nextJ in 0 until n && !visit[nextI][nextJ]) {
i = nextI
j = nextJ
visit[i][j] = true
ans.add(matrix[i][j])
} else {
index = (index + 1) % 4
}
}
return ans
}