itisjustK
코딩과 사람 사는 이야기
itisjustK
전체 방문자
오늘
어제
  • 분류 전체보기 (207)
    • 일이삼사오육칠팔구십일이삼사오육칠팔구십일이삼사오육칠.. (0)
    • Web (43)
      • html & css (9)
      • django & python (15)
      • java script (9)
    • iOS (51)
      • Swift (42)
      • SwiftUI (5)
    • CS (25)
      • 자료구조 (6)
      • 운영체제 (3)
      • 데이터베이스 (9)
      • 네트워크 (7)
    • PS (34)
      • 알고리즘 & 자료구조 (0)
    • Life (36)
    • Retrospective (15)
    • Book (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 연결리스트
  • 생활코딩 #이고잉 #HTML #코딩 #개발자
  • 킨디
  • ios
  • mongodb
  • 독립서점
  • 생활코딩
  • AppleDevloperAcademy
  • 세그멘테이션
  • POSTECH
  • SWIFT
  • 개발자
  • crud
  • SwiftUI
  • 어플
  • CoreData
  • CS
  • nosql
  • binding
  • 점주

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
itisjustK

코딩과 사람 사는 이야기

[Leetcode - Swift] 841. Keys and Rooms
PS

[Leetcode - Swift] 841. Keys and Rooms

2023. 2. 20. 14:09

문제

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와 BFS 둘 다 가능하다.

DFS의 런타임은 35ms로, 38ms인 BFS보다 더 빨랐다. 메모리도 0.1MB 덜 써서 공간복잡도에서도 효율적이었다.

 

BFS와 DFS의 템플릿을 그대로 이용하는 기본적인 문제였다. 기본의 중요성을 다시 한 번 느낀다!

 

👇🏻 BFS와 DFS 템플릿 보러가기

 

[PS] 간단한 Graph 개념과 BFS, DFS 템플릿

Graph 그래프는 정점(vertex)과 간선(edge)의 집합이다. G(V,E)로 표현할 수 있다. 그래프의 종류에는 방향 그래프와 무향 그래프(PS에서 가장 많이 등장), 다중 그래프와 단순 그래프, 가중치 그래프(다

newwave.tistory.com

 

코드

import Foundation

class Solution {
    // dfs by 재귀
    func canVisitAllRooms(_ rooms: [[Int]]) -> Bool {
        var visited = [Int]()
        
        func dfs(_ current: Int) {
            visited.append(current)
            
            for room in rooms[current] {
                if !visited.contains(room) {
                    dfs(room)
                }
            }
        }
        
        dfs(0)
        return visited.count == rooms.count
    }
    
    //bfs by 큐
    func canVisitAllRooms2(_ rooms: [[Int]]) -> Bool {
        return bfs(rooms, 0).count == rooms.count
    }
    
    func bfs(_ rooms: [[Int]], _ start: Int) -> [Int] {
        var visited = [start], queue = [start]
        
        while !queue.isEmpty {
            let current = queue.removeFirst()
            
            for room in rooms[current] {
                if !visited.contains(room) {
                    queue.append(room)
                    visited.append(room)
                }
            }
        }
        return visited
    }
}
저작자표시 (새창열림)

'PS' 카테고리의 다른 글

[프로그래머스 - Swift] 가장 먼 노드  (0) 2023.02.21
[프로그래머스 - Swift] 네트워크  (0) 2023.02.20
[PS] 간단한 Graph 개념과 BFS, DFS 템플릿  (0) 2023.02.20
[Leetcode - Swift] 1091 Shortest Path in Binary Matrix  (0) 2023.02.18
[프로그래머스 - Swift] 오픈 채팅방 (2019 KAKAO BLIND RECRUITMENT)  (0) 2023.02.15
    'PS' 카테고리의 다른 글
    • [프로그래머스 - Swift] 가장 먼 노드
    • [프로그래머스 - Swift] 네트워크
    • [PS] 간단한 Graph 개념과 BFS, DFS 템플릿
    • [Leetcode - Swift] 1091 Shortest Path in Binary Matrix
    itisjustK
    itisjustK

    티스토리툴바