[Algorithm] ์์
hwangJi-dev opened this issue ยท 0 comments
hwangJi-dev commented
๐ฌ ๋ฌธ์
https://school.programmers.co.kr/learn/courses/30/lessons/49191
๐ฌ Idea
- ์ด๊ธฐ๋ ๊ฒฝ์ฐ๋ฅผ ํ์ํ ์ ์๋ winGraph์, ์ง๋ ๊ฒฝ์ฐ๋ฅผ ํ์ํ ์ ์๋ loseGraph๋ฅผ ๊ฐ๊ฐ ๋ง๋ ๋ค.
- 1๋ถํฐ N๊น์ง ๊ฐ๊ฐ winGraph, loseGraph๋ฅผ ํ์ํ๋ฉฐ ์ด๊ธด ๊ฒฝ์ฐ์ ์ง ๊ฒฝ์ฐ์ ํ์ ๊ฒฐ๊ณผ๋ฅผ ๋์ถํ๋ค.
- ์ด๊ธด ๊ฒฝ์ฐ์ ์ง ๊ฒฝ์ฐ์ ํ์ ๊ฒฐ๊ณผ๋ฅผ ํฉ์ณค์ ๋ 1๋ถํฐ N๊น์ง์ ์ซ์๊ฐ ๋ชจ๋ ํฌํจ๋๋ค๋ฉด ์์๋ฅผ ์ ์ ์๋ ์ ์๋ผ๋ ์์ด๋์ด๋ฅผ ๋ ์ฌ๋ ค
Set ์๋ฃ๊ตฌ์กฐ๋ฅผ ํ์ฉํ์ฌSet(win + lose).count == n
์ด๋ผ๋ฉด ๊ฒฐ๊ณผ๊ฐ์ +1์ ํด์ฃผ์๋ค.
๐ฌ ํ์ด
import Foundation
func solution(n:Int, results:[[Int]]) -> Int {
var loseGraph: [Int: [Int]] = [:]
var winGraph: [Int: [Int]] = [:]
var ans = 0
for i in results {
if loseGraph[i[1]] == nil {
loseGraph[i[1]] = [i[0]]
} else {
loseGraph[i[1]]?.append(i[0])
}
if winGraph[i[0]] == nil {
winGraph[i[0]] = [i[1]]
} else {
winGraph[i[0]]?.append(i[1])
}
}
func dfs(_ isWin: Bool, _ start: Int) -> [Int] {
var visitedQueue: [Int] = []
var neetToVisitStack: [Int] = [start]
while !neetToVisitStack.isEmpty {
let node = neetToVisitStack.removeLast()
if visitedQueue.contains(node) { continue }
visitedQueue.append(node)
if isWin {
neetToVisitStack += winGraph[node] ?? []
} else {
neetToVisitStack += loseGraph[node] ?? []
}
}
return visitedQueue
}
for i in 1...n {
let win = dfs(true, i)
let lose = dfs(false, i)
if Set(win + lose).count == n {
ans += 1
}
}
return ans
}