
思路
- 用行指针
h,列指针v来控制遍历范围,遍历上下左右四个边。
- 用
count记录遍历过的元素个数,控制count小于元素总个数m*n。
- 注意可能存在的重复遍历:当只剩下一行时。

class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int length = matrix[0].length, width = matrix.length;
int total = width * length;
int count = 0;
int top = 0, bottom = width - 1, left = 0, right = length - 1;
while (count < total) {
for (int i = left; i <= right; i++) {
res.add(matrix[top][i]);
count++;
}
for (int i = top + 1; i < bottom; i++) {
res.add(matrix[i][right]);
count++;
}
for (int i = right; i >= left && top != bottom; i--) {
res.add(matrix[bottom][i]);
count++;
}
for (int i = bottom - 1; i > top && left != right; i--) {
res.add(matrix[i][left]);
count++;
}
top++;
bottom--;
left++;
right--;
}
return res;
}
}
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int u = 0, v = matrix[0].length - 1, m = 0, n = matrix.length - 1
int size = matrix[0].length * matrix.length
List<Integer> res = new ArrayList<>()
int count = 0
while (count < size) {
for (int i = u
res.add(matrix[m][i])
count++
}
for (int i = m + 1
res.add(matrix[i][v])
count++
}
if (count < size) {
for (int i = v
res.add(matrix[n][i])
count++
}
}
if (count < size) {
for (int i = n - 1
res.add(matrix[i][u])
count++
}
}
u++
v--
m++
n--
}
return res
}
}