# 54. Spiral Matrix

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MfRvt_MNYbvpmYqlHAY%2F-MfS8mEBLoMpWNwYOF-p%2Fimage.png?alt=media\&token=b7859fe1-bf97-4a4a-bac6-c57a3026854a)

time: O(mn)

space: O(mn)



why&#x20;

```java
if (rowStart <= rowEnd) { 
// 因為前面有 rowStart++ 和 colEnd--, 值有改動, 所以避免在 while 內邊界超過
// 所以要多加判斷
if (colStart <= colEnd) {
```

```java
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        
        List<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0) return res;
        
        int rowStart = 0;
        int rowEnd = matrix.length - 1;
        int colStart = 0;
        int colEnd = matrix[0].length - 1;

        
        while (colStart <= colEnd && rowStart <= rowEnd) {
            
            if (rowStart <= rowEnd) { //都加
                for (int i = colStart; i <= colEnd; i++) {
                    res.add(matrix[rowStart][i]);
                }
            }
            rowStart++;
            
            if (colStart <= colEnd) { //都加
                for (int i = rowStart; i <= rowEnd; i++) { 
                    res.add(matrix[i][colEnd]);
                }
            }
            colEnd--;
            
            if (rowStart <= rowEnd) { //都加
                for (int i = colEnd; i >= colStart; i--) {
                    res.add(matrix[rowEnd][i]);
                }
            }
            rowEnd--;
            
            if (colStart <= colEnd) { //都加
                for (int i = rowEnd; i >= rowStart; i--) {
                    res.add(matrix[i][colStart]);
                }
            }
            colStart++;
            
        }
        return res;
    }
}
```
