LeetCode/com/zerroi/leetcode/Three16/SpiralOrder.java

46 lines
1.2 KiB
Java
Raw Permalink Normal View History

2024-03-21 19:03:41 +08:00
package com.zerroi.leetcode.Three16;
import java.util.ArrayList;
import java.util.List;
public class SpiralOrder {
}
class SolutionSecond {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int left = 0, right = matrix.length;
int top = 0, bottom = matrix[0].length;
int len = right * bottom;
int i = 0;
while (i < len) {
for (int j = left; j < right; j++) {
res.add(matrix[top][j]);
++i;
if (i >= len) return res;
}
++top;
for (int j = top; j < bottom; j++) {
res.add(matrix[j][right - 1]);
++i;
if (i >= len) return res;
}
--right;
for (int j = right - 1; j >= left; j--) {
res.add(matrix[bottom-1][j]);
++i;
if (i >= len) return res;
}
++left;
for (int j = bottom - 1; j >= top; j--) {
res.add(matrix[j][left]);
++i;
if (i >= len) return res;
}
--bottom;
}
return res;
}
}