题目链接
法一
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new LinkedList<>();
int row = matrix.length, col = matrix[0].length;
if (row == 0 || col == 0) return ans;
int up = 0, down = row - 1, left = 0, right = col - 1;
while (true) {
for (int i = left; i <= right; i++) ans.add(matrix[up][i]);
if (++up > down) break;
for (int i = up; i <= down; i++) ans.add(matrix[i][right]);
if (--right < left) break;
for (int i = right; i >= left; i--) ans.add(matrix[down][i]);
if (--down < up) break;
for (int i = down; i >= up; i--) ans.add(matrix[i][left]);
if (++left > right) break;
}
return ans;
}
本地测试
lay.showTitle(54);
Solution54 sol54 = new Solution54();
int[][] matrix54 = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
arrayOpt.showIntTwoDimArray(matrix54, matrix54.length);
System.out.println(sol54.spiralOrder(matrix54).toString());