题目:
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元
素。
示例1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出:[1,2,3,6,9,8,7,4,5]
java:
public class LeetCode054 {
public static List<Integer> spiralOrder(int[][] matrix) {
//存放数组的数.
List<Integer> ans = new ArrayList<>();
//列数.
int columns = matrix[0].length;
//行数
int rows = matrix.length;
//遍历起点.
int start = 0;
//循环次数 行数和列数最小值除以2.
int loop = Math.min(rows, columns) / 2;
int mid = loop;
//终止条件.
int offset = 1;
int i, j;
while (loop-- > 0) {
i = j = start;
//从左往右.
for (; j < columns - offset; j++) {
ans.add(matrix[i][j]);
}
//从上往下.
for (; i < rows - offset; i++) {
ans.add(matrix[i][j]);
}
//从右往左.
for (; j > start; j--) {
ans.add(matrix[i][j]);
}
//从下往上.
for (; i > start; i--) {
ans.add(matrix[i][j]);
}
//循环一次.改变起点位置.
start++;
//终止条件改变.
offset++;
}
//如果行和列中最小值是奇数.则会产生中间行或者中间列没有遍历.
if (Math.min(rows, columns) % 2 != 0) {
//行大于中间列则产生中间列.
if (rows > columns) {
for (int k = mid; k < mid + rows - columns + 1; k++) {
ans.add(matrix[k][mid]);
}
} else {
//列大于行.产生中间行.
for (int k = mid; k < mid + columns - rows + 1; k++) {
ans.add(matrix[mid][k]);
}
}
}
return ans;
}
public static void main(String[] args) {
int[][] nums = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
List<Integer> order = spiralOrder(nums);
System.out.println(order);
}
}
山水有相逢.
如果大家喜欢我的分享的话.可以关注我的微信公众号
念何架构之路