Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions linked-list-cycle/radiantchoi.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/

// 1차 버전: 문제의 constraint에 따라 1만 번의 traverse를 수행하는 답안 (통과는 됩니다)
class Solution {
func hasCycle(_ head: ListNode?) -> Bool {
guard let head else { return false }

return traverse(head, 0)
}

func traverse(_ node: ListNode?, _ currentIndex: Int) -> Bool {
guard let node else { return false }
guard currentIndex < 10000 else { return true }

return traverse(node.next, currentIndex + 1)
}
}

// LLM 첨삭 버전: Floyd's Cycle Detection Algorithm 사용
class Solution {
func hasCycle(_ head: ListNode?) -> Bool {
guard let head else { return false }

var slow: ListNode? = head
var fast: ListNode? = head

while true {
// fast는 한 번에 두 칸씩 이동
fast = fast?.next?.next

// slow는 한 번에 한 칸씩 이동
slow = slow?.next

// fast나 slow가 nil이면 cycle이 없다
if fast == nil || slow == nil { return false }

// fast와 slow가 같은 노드를 가리키면 cycle이 있다
// break로 마무리한 이유는, 그래서 그 만나는 노드가 어디인가? 라는 문제에 응용하기 위함
if fast === slow { break }
}

// 사이클 시작 지점을 찾는 문제일 경우 여기에 entry 포인터 삽입 후 탐색

return true
}
}

/*
사이클 시작 지점을 찾으시오, 라는 문제일 경우?
entry라는 별도의 포인터를 하나 더 둔 다음 slow와 함께 한 칸씩 이동시킨다.
두 포인터가 만나는 지점이 사이클 시작 지점!
이것이 가능한 이유는, 아래의 이동 거리 공식 때문에 그렇다.

L: 사이클 입구까지의 길이
C: 사이클 길이
d: 사이클 내에서, 사이클 종료(==시작)까지 남은 거리

fast의 이동 거리: L + n * C + d
slow의 이동 거리: L + d

fast의 이동 거리는 slow의 이동 거리의 2배이므로
2 * (L + d) = L + n * C + d

따라서, L = n * C - d 이다.
그리고 L은 entry 포인터가 이동해야 하는 거리이다.
n * C - d는 사이클 안에서는 C - d와 같다. fast 노드가 n번 돌았을 뿐, 사이클 안이었기 때문.
따라서 entry 포인터와 slow 포인터를 다시 한 칸씩 이동시키다 보면, 반드시 만나게 된다.
이 만나는 지점이 사이클 시작 지점.
*/
Comment on lines +58 to +79
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제를 확장해서도 생각 하셨네요!

덕분에, 시작 지점 찾는 방법 배워가요 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사실 이번에 Floyd's cycle detection algorithm이라는 걸 아예 처음 접하다 보니, 결국 만나는 지점을 찾아서 어디다 쓰지? 라는 의문이 들었습니다. 그리고 역시나, 그런 문제가 있긴 하더라구요. 도움이 되셨다니 기쁩니다.

49 changes: 49 additions & 0 deletions pacific-atlantic-water-flow/radiantchoi.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// 힌트를 받은 아이디어: 특정 칸에서 흘러내려가는 것이 아니라, 바다에서부터 거슬러 올라가는 것을 계산하면 어떨까?

class Solution {
func pacificAtlantic(_ heights: [[Int]]) -> [[Int]] {
var result = [[Int]]()
var pacificMap = Array(repeating: Array(repeating: false, count: heights[0].count), count: heights.count)
var atlanticMap = Array(repeating: Array(repeating: false, count: heights[0].count), count: heights.count)

for k in 0..<heights[0].count {
traverse(heights, 0, k, 0, &pacificMap)
}

for l in 0..<heights.count {
traverse(heights, l, 0, 0, &pacificMap)
}

for m in 0..<heights[0].count {
traverse(heights, heights.count - 1, m, 0, &atlanticMap)
}

for n in 0..<heights.count {
traverse(heights, n, heights[0].count - 1, 0, &atlanticMap)
}

for i in 0..<heights.count {
for j in 0..<heights[i].count {
if pacificMap[i][j] && atlanticMap[i][j] {
result.append([i, j])
}
}
}

return result
}

func traverse(_ heights: [[Int]], _ row: Int, _ col: Int, _ previous: Int, _ reachabilities: inout [[Bool]]) {
guard (0..<heights.count) ~= row && (0..<heights[0].count) ~= col else { return }

guard heights[row][col] >= previous else { return }
guard !reachabilities[row][col] else { return }

reachabilities[row][col] = true

traverse(heights, row - 1, col, heights[row][col], &reachabilities)
traverse(heights, row + 1, col, heights[row][col], &reachabilities)
traverse(heights, row, col - 1, heights[row][col], &reachabilities)
traverse(heights, row, col + 1, heights[row][col], &reachabilities)
}
}