[LeetCode]Spiral Matrix II

2023. 5. 23. 20:43·SW개발/코딩테스트

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

 

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

 

문제 분석

n의 값이 주어지는 n*n matrix에서 Sprial 순서대로 탐색을 했을 경우의 matrix를 만드는 문제입니다.

 

처음 시도한 답안

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        row_begin = 0
        col_begin = 0

        row_end = n-1
        col_end = n-1

        answer = [[0] * n for _ in range(n)]
        count = 1

        while row_begin <= row_end and col_begin <= col_end:
            for i in range(col_begin, col_end+1):
                answer[row_begin][i] = count
                count += 1
            row_begin += 1

            for i in range(row_begin, row_end+1):
                answer[i][col_end] = count
                count += 1
            col_end -= 1

            if row_begin <= row_end:
                for i in range(col_end, col_begin-1, -1):
                    answer[row_end][i] = count
                    count += 1
                row_end -= 1

            if col_begin <= col_end:
                for i in range(row_end, row_begin-1, -1):
                    answer[i][col_begin] = count
                    count += 1
                col_begin += 1
    
        return answer

접근 방법

  1. 이 문제의 경우 지난 Spiral Matrix 문제와 매우 유사합니다.
  2. 먼저 주어진 n을 가지고 n*n matrix를 만들어 줍니다.
  3. Spiral 탐색을 하면서 count를 매번 증가시키고, 그 값을 answer matrix에 계속 기록합니다.
  4. matrix를 복구할 수 있습니다.

지난번에 풀이를 올렸던 해당 문제와 매우 유사합니다. 다만, count를 증가시키면서 값을 기록했습니다.

 

https://leffept.tistory.com/494

 

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Minimum Path Sum  (0) 2023.05.25
[LeetCode]Jump Game  (0) 2023.05.24
[LeetCode]Spiral Matrix  (0) 2023.05.22
[LeetCode]Maximum Subarray  (0) 2023.05.21
[LeetCode]Group Anagrams  (0) 2023.05.10
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Minimum Path Sum
  • [LeetCode]Jump Game
  • [LeetCode]Spiral Matrix
  • [LeetCode]Maximum Subarray
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (308) N
      • SW개발 (304) N
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (2) N
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    음식
    오픈소스
    어플리케이션
    g
    Contributor
    배공파용
    라이프 스타일
    배달비 공유
    배달
    django
    컨트리뷰터
    트리 #AVL #알고리즘 #자료구조
    플레이스토어
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Spiral Matrix II
상단으로

티스토리툴바