Spiral Matrix - LeetCode

 

Spiral Matrix - 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

 

이게 medium이라구? 너무 쉬운데..

그냥 시뮬레이션 하면 된다 별다른 설명이 필요 없음.

현재 칸에서 주위 네 방향 다 invalid하다 싶으면 그 때 시뮬레이션을 종료하면 된다.

 

class Solution:
    
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        dx = [0, 1, 0, -1]
        dy = [1, 0, -1, 0]
        
        result = []
        
        x = 0
        y = -1
        i = 0
        invalid_count = 0
        
        while True:
            nx = x + dx[i]
            ny = y + dy[i]
            
            

            #다음칸이 valid 하면
            if nx >= 0 and nx < len(matrix) and ny >= 0 and ny < len(matrix[0]) and matrix[nx][ny] != -101:
                invalid_count = 0
                result.append(matrix[nx][ny])
                matrix[nx][ny] = -101
                x = nx
                y = ny
            else: #invalid 하면
                i = (i + 1) % 4
                invalid_count += 1
            

            # 4방향ㅇ 다 invalid하면 시뮬레이션 종료
            if invalid_count == 4:
                break
                
        return result
            
            
                

 

+ Recent posts