
문제
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 |