1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package com.leetcode;
import java.util.LinkedList; import java.util.List;
public class SpiralMatrix54 { public static void main(String[] args) { System.out.println(new Solution().spiralOrder(new int[][]{{2, 5, 8}, {4, 0, -1}})); }
private static class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list = new LinkedList<>(); doSpiralARound(matrix, 0, 0, matrix[0].length, matrix.length, list); return list; }
private void doSpiralARound(int[][] matrix, int x, int y, int length, int height, List<Integer> res) { if (length <= 0 || height <= 0 || x > matrix.length - 1 || y > matrix[0].length - 1) return; for (int i = 0; i < length; i++) { res.add(matrix[x][y + i]); } for (int i = 1; i < height; i++) { res.add(matrix[x + i][y + length - 1]); } if (height > 1) { for (int i = length - 2; i >= 0; i--) { res.add(matrix[x + height - 1][y + i]); } if (length > 1) for (int i = height - 2; i > 0; i--) { res.add(matrix[x + i][y]); } } doSpiralARound(matrix, x + 1, y + 1, length - 2, height - 2, res); } } }
|