Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1 :

1

2

3

4

5

6

7

8

9

Input : matrix = [[1,2,3],[4,5,6][7,8,9]] Output : [1,2,3,6,9,8,7,4,5]

Example 2 :

1

2

3

4

5

6

7

8

9

10

11

12

Input : matrix = [[1,2,3,4],[5,6,7,8][9,10,11,12]] Output : [1,2,3,4,8,12,11,10,9,5,6,7,8]

자료구조 : List와 변수 4개 이용(rowStart,rowEnd,colStart,colEnd) 알고리즘 1. 행과 열이 어떻게 변화하는지 본다. 2. 행과 열이 바뀔 때마다 그다음 증감식의 범위가 바뀌기 때문에 이 범위를 체크하기 위해 rowStart,rowEnd,colStart,colEnd를 이용한다!

알고리즘을 java로 구현

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        //1. 그릇 생성
        int rowStart = 0,colStart = 0;
        int rowEnd = matrix.length-1;//3-1=2.
        int colEnd = matrix[0].length-1;//4-1=3.
        List<Integer> result = new ArrayList<>();
        if(matrix == null || matrix.length == 0) return result;
        
        while(rowStart <= rowEnd && colStart <= colEnd) {
            //right. 행고정, 열증가
            for(int i=colStart; i <= colEnd; i++) {
                result.add(matrix[rowStart][i]);
            }
            rowStart++;
            //down. 열고정, 행증가
            for(int i=rowStart; i <= rowEnd; i++) {
                result.add(matrix[i][colEnd]);
            }
            colEnd--;
            //left. 행고정, 열감소!
            if(rowStart <= rowEnd) {
                for(int i=colEnd; i >= colStart ;i--) {
                    result.add(matrix[rowEnd][i]);
                }
            }
            rowEnd--;//rowStart < rowEnd!!!
            //up. 열고정, 행감소!
            if(colStart <= colEnd) {
                if(rowStart <= rowEnd) {
                    for(int i = rowEnd; i >= rowStart; i--) {
                        result.add(matrix[i][colStart]);
                    }
                }
            }
            colStart++;//colStart < colEnd!!!
            // //2nd right. 행고정, 열증가!
            // for(int i= colStart; i <= colEnd ; i++) {
            //     result.add(matrix[rowStart][i]);
            // }
      }  
        return result;
    }
}

Last updated

Was this helpful?