본문으로 바로가기

Description

나선형으로 정렬된 n*n행렬을 새성하여 반환하는 문제입니다.

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= n <= 20

Solution 1. Iteration

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

    int[][] matrix = new int[n][n];
    if (n <= 0) return matrix;

    int num = 1;
    int rowbegin = 0, rowend = n-1;
    int colbegin = 0, colend = n-1;
    while (rowbegin <= rowend && colbegin <= colend) {
        for (int i = colbegin; i <= colend; i++) matrix[rowbegin][i] = num++; //12시
        rowbegin++;

        for (int i = rowbegin; i <= rowend; i++) matrix[i][colend] = num++; //3시
        colend--;

        for (int i = colend; i >= colbegin; i--) matrix[rowend][i] = num++; // 6시
        rowend--;

        for (int i = rowend; i >= rowbegin; i--) matrix[i][colbegin] = num++; // 9시
        colbegin++;
    }
    return matrix;
}

나선형으로 12시 3시 6시 9시 순서대로 Row와 Column을 하나씩 줄여나가며 기록해 나갑니다.

Reference

 

Spiral Matrix II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com