Spiral Matrix

Edit

Difficulty: MEDIUM

Categories: 배열/문자열

Source: https://leetcode.com/problems/spiral-matrix/


Solutions

Add Solution
JAVA 2026-10-03 12:00 Edit
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if(matrix == null || matrix.length == 0) return result;
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;
        while(top <= bottom && left <= right) {
            for(int i = left; i <= right; i++) result.add(matrix[top][i]);
            top++;
            for(int i = top; i <= bottom; i++) result.add(matrix[i][right]);
            right--;
            if(top <= bottom) {
                for(int i = right; i >= left; i--) result.add(matrix[bottom][i]);
                bottom--;
            }
            if(left <= right) {
                for(int i = bottom; i >= top; i--) result.add(matrix[i][left]);
                left++;
            }
        }
        return result;
    }
}
Notes:

[자동 풀이 · gpt-4.1-mini] 4개의 경계(top, bottom, left, right)를 설정하고, 경계를 좁혀가며 시계방향으로 배열을 순회한다. 각 방향(왼->오, 위->아래, 오->왼, 아래->위)으로 이동하며 요소를 결과 리스트에 추가하고, 경계를 한 칸씩 좁힌다. 경계가 겹칠 때까지 반복한다. 시간 O(m*n) m: 행, n: 열 · 공간 O(m*n) 결과 리스트 저장 공간 주의: 경계 조건(top<=bottom, left<=right) 체크를 빼먹으면 중복 추가나 인덱스 오류 발생