본문 바로가기
LeetCode

[LeetCode] 59. Spiral Matrix II

by JungSeung 2023. 12. 29.
728x90

https://leetcode.com/

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.


Example 1:

출처 : https://leetcode.com/problems/spiral-matrix-ii/

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

 

Example 2:

Input: n = 1
Output: [[1]]

 

Constraints:

  • 1 <= n <= 20

 

Code :

var generateMatrix = function(n) {
    // 행렬 초기화
    const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0));
    let top = 0, bottom = n - 1, left = 0, right = n - 1;
    let num = 1;

    // 반시계방향으로 나선형 순서로 행렬 채우기
    while (top <= bottom && left <= right) {
        // 위쪽 행
        for (let i = left; i <= right; i++) {
            matrix[top][i] = num;
            num++;
        }
        top++;

        // 오른쪽 열
        for (let i = top; i <= bottom; i++) {
            matrix[i][right] = num;
            num++;
        }
        right--;

        // 아래쪽 행
        if (top <= bottom) {
            for (let i = right; i >= left; i--) {
                matrix[bottom][i] = num;
                num++;
            }
            bottom--;
        }

        // 왼쪽 열
        if (left <= right) {
            for (let i = bottom; i >= top; i--) {
                matrix[i][left] = num;
                num++;
            }
            left++;
        }
    }
    return matrix;
};

 

Solutions Code :

var generateMatrix = function(n) {
    // n x n 크기의 2차원 배열을 생성하고 모든 요소를 0으로 초기화
    let save = Array.from(Array(n), () => new Array(n).fill(0));
    
    // 숫자를 세기 위한 변수 초기화
    let count = 1;
    
    // 매트릭스의 네 방향 경계를 나타내는 변수 초기화
    let left = 0;
    let right = n - 1;
    let bottom = n - 1;
    let top = 0;
    
    // 현재 방향을 나타내는 변수 초기화 (0: 오른쪽, 1: 아래, 2: 왼쪽, 3: 위)
    let dir = 0;

    // 모든 칸을 채울 때까지 반복
    while (count <= n * n) {
        // 오른쪽 방향으로 이동
        if (dir == 0) {
            for (let i = left; i <= right; i++) {
                save[top][i] = count;
                count++;
            }
            top++;
            dir++;
        }
        // 아래쪽 방향으로 이동
        else if (dir == 1) {
            for (let i = top; i <= bottom; i++) {
                save[i][right] = count;
                count++;
            }
            right--;
            dir++;
        }
        // 왼쪽 방향으로 이동
        else if (dir == 2) {
            for (let i = right; i >= left; i--) {
                save[bottom][i] = count;
                count++;
            }
            bottom--;
            dir++;
        }
        // 위쪽 방향으로 이동
        else if (dir == 3) {
            for (let i = bottom; i >= top; i--) {
                save[i][left] = count;
                count++;
            }
            left++;
            dir = 0;
        }
    }

    // 생성된 매트릭스 반환
    return save;
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 61. Rotate List  (2) 2024.01.09
[LeetCode] 60. Permutation Sequence  (0) 2023.12.29
[LeetCode] 58. Length of Last Word  (0) 2023.12.28
[LeetCode] 57. Insert Interval  (0) 2023.12.27
[LeetCode] 56. Merge Intervals  (0) 2023.12.27