Loading Question... - LeetCode

 

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

 

한 변의 크기 n이 주어졌을 때 나선형으로 숫자가 증가하는 N*N matrix를 리턴하면 되는문제다.

간단한 시뮬레이션으로 해결 가능.

근데 지금 리트코드 서버가 갑자기 터져서 정답이 맞는지 체크는 못해봄..

 

class Solution:
    def generateMatrix(self, n: int):
        
        matrix = [[0] * n for _ in range(n)]
        
        dx = [0, 1, 0, -1]
        dy = [1, 0, -1, 0]
        
        direction = 0
        
        x, y = 0, 0
        
        for i in range(1, n * n + 1):
            matrix[x][y] = i
            
            nx = x + dx[direction]
            ny = y + dy[direction]
            
            if nx < 0 or nx >= n or ny < 0 or ny >= n or matrix[nx][ny] != 0:
                direction = (direction + 1) % 4
                nx = x + dx[direction]
                ny = y + dy[direction]
                
            x = nx
            y = ny
            
        return matrix

+ Recent posts