Step-by-Step

[Java] Daily LeetCode Challenge 59. Spiral Matrix II 본문

언어/JAVA

[Java] Daily LeetCode Challenge 59. Spiral Matrix II

희주(KHJ) 2023. 5. 10. 18:54

https://leetcode.com/problems/spiral-matrix-ii/description/

 

Spiral Matrix II - LeetCode

Can you solve this real interview question? Spiral Matrix II - Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.   Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg] Input: n = 3 O

leetcode.com

 

흔한 시뮬레이션 문제 

체감 난이도는 Easy같다.

for 문으로 일일이 지정해주는것보다 while문으로 증감 연산자 사용해주는게 더 가독성 좋고 효율적인거같다!

 

[코드]

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];

        int num = 1; 

        for(int i=0; i<n; i++)
            ans[0][i]=num++;

        int m = n, x=0, y=n-1;
        while(m >= 1) {
            m--;

            // 아래
            int cnt = m;
            while(cnt-- > 0)
                ans[++x][y]=num++;

            // 왼
            cnt = m;
            while(cnt-- > 0)
                ans[x][--y]=num++;
            
            m--;
			
            // 위
            cnt = m;
            while(cnt-- > 0)
                ans[--x][y]=num++;

            // 오
            cnt = m;
            while(cnt-- > 0)
                ans[x][++y]=num++;
        }

        return ans;
    }
}

 

Comments