waveofmymind
기록하는 습관
waveofmymind
전체 방문자
오늘
어제
  • 분류 전체보기 (124)
    • 📝 정리 (5)
    • 🌊TIL (9)
    • 💻CS (1)
      • 자료구조 (1)
    • 📙Language (9)
      • ☕Java (6)
      • 🤖Kotlin (3)
    • 🍃Spring (28)
    • 👨🏻‍💻알고리즘 (67)
      • 프로그래머스 (59)
      • 백준 (3)
    • 👷DevOps (4)
      • 🐳Docker (2)
      • 🤵Jenkins (1)

블로그 메뉴

  • 홈
  • Spring
  • Java
  • 알고리즘

공지사항

인기 글

태그

  • chat GPT
  • Open AI
  • Spring Security
  • 코틀린
  • 힙
  • 스프링 부트
  • spring boot
  • spring
  • 트랜잭션 전파
  • resultset
  • 트랜잭션
  • AOP
  • til
  • 스프링 시큐리티
  • 챗GPT
  • JDBC
  • kotlin
  • Connection
  • 다이나믹 프로그래밍
  • kotest
  • sql
  • 스택
  • 스프링
  • BFS
  • SpringAOP
  • mybatis
  • 통합테스트
  • CORS
  • LeetCode
  • 완전탐색

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
waveofmymind

기록하는 습관

[LeetCode] 841. Keys and Rooms
👨🏻‍💻알고리즘

[LeetCode] 841. Keys and Rooms

2023. 2. 24. 23:30

문제 링크: https://leetcode.com/problems/keys-and-rooms/description/

 

Keys and Rooms - LeetCode

Keys and Rooms - There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of di

leetcode.com

코드

  • DFS
class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        visited = set() 

   
        def dfs(v):
            visited.add(v)
            for next_v in rooms[v]:
                if next_v not in visited:
                    dfs(next_v)



        dfs(0)
        if len(visited) == len(rooms) : return True
        else: return False
  • BFS
from collections import deque
class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        visited = set() #5번방 방문 안했네 => False  // True
        
        def bfs(v):
            visited.add(v)
            q = deque()
            q.append(v)
            while q:
                tmp = q.popleft()
                for i in rooms[tmp]:
                    if i not in visited:
                        visited.add(i)
                        q.append(i)
        bfs(0)
        if len(visited) == len(rooms) : return True
        else: return False

풀이

  • DFS,BFS를 짤 줄 안다면 쉽게 풀 수 있다.
  • visited를 set으로 초기화한 이유는, 조건문에서 찾고자 하는 값이 배열에 있는지 확인할 때의 시간 복잡도를 줄이기 위해서이다.
  • 파이썬에서 딕셔너리와 셋은 해시로 이루어져 있기 때문에 in 으로 찾을때 시간 복잡도가 O(1) 이다.
  • 리스트의 경우, 순서가 있기 때문에 in 으로 찾을 때의 시간복잡도는 O(n)으로 효율이 좋지 않다.
  • dfs,bfs를 진행할 때 visited를 통해 방문했는지 안했는지를 조건문을 통해 확인하면 된다.

'👨🏻‍💻알고리즘' 카테고리의 다른 글

[LeetCode] 70. Climbing Stairs  (0) 2023.02.28
[LeetCode] 1091. Shortest Path in Binary Matrix  (0) 2023.02.24
[LeetCode] 200. Number of Islands  (0) 2023.02.24
[LeetCode] Medium. Daily Temperatures  (1) 2023.02.16
    '👨🏻‍💻알고리즘' 카테고리의 다른 글
    • [LeetCode] 70. Climbing Stairs
    • [LeetCode] 1091. Shortest Path in Binary Matrix
    • [LeetCode] 200. Number of Islands
    • [LeetCode] Medium. Daily Temperatures
    waveofmymind
    waveofmymind

    티스토리툴바