본문 바로가기

LeetCode 59. Spiral Matrix 2 본문

LeetCode

LeetCode 59. Spiral Matrix 2

00rigin 2025. 1. 19. 21:35

https://leetcode.com/problems/spiral-matrix-ii/description/?envType=problem-list-v2&envId=simulation

 

제한된 2차원 배열 공간 안에서 뱅글뱅글 도는 규칙이 있을 경우, 벽이 있다고 생각하면 쉽다.

row의 start와 end, column의 start와 end를 기준으로 벽이 있다고 생각하고, 한 줄 (가로든, 세로든) 을 채울때 마다 벽이 한칸씩 조여지는 느낌으로 생각하면 까먹지 않을 것 같다.

 

class Solution {
    public int[][] generateMatrix(int n) {

        int[][] res = new int[n][n];
        int counter = 1;

        int col_start = 0;
        int col_end = n-1;
        int row_start = 0;
        int row_end = n-1;

        while(col_start <= col_end && row_start <= row_end) {
            // row_s 고정
            for(int i = col_start; i<=col_end; i++) {
                res[row_start][i] = counter;
                counter++;
            }
            row_start++;

            // col_e 고정
            for(int i = row_start; i<= row_end; i++) {
                res[i][col_end] = counter;
                counter++;
            }
            col_end--;

            // row_e 고정
            for(int i = col_end; i>= col_start; i--){
                res[row_end][i] = counter;
                counter++;
            }
            row_end--;

            // col_s 고정
            for(int i = row_end; i>= row_start; i--){
                res[i][col_start] = counter;
                counter++;
            }
            col_start++;
        }

        if((row_start == row_end) &&  (col_start == col_end)){
            res[row_start][col_start] = counter;
        }

        return res;

    }
}
Comments