DFS를 통해 재귀적으로 백트래킹하는 문제. 중복 방문이 가능하기 때문에 현재 양/늑대의 개수를 파라미터로 전달하면서 최댓값을 갱신한다. 이때 방문하지 않은 상태의 자식 노드가 양인지 늑대인지
info를 통해 확인, 다음 DFS에 넘길 파라미터를 맞춰준다.
visited 해놓은 곳에서는 아무런 합산이 이루어지지 않기 때문이다. import Foundation
func solution(_ info:[Int], _ edges:[[Int]]) -> Int {
var total = 0
var visited = Array(repeating: false, count: info.count)
visited[0] = true
DFS(1, 0)
func DFS(_ curSheep: Int, _ curWolf: Int) {
if curSheep <= curWolf {
return
} else {
total = max(total, curSheep)
}
for edge in edges {
let parent = edge[0]
let child = edge[1]
let nextState = info[child] == 0 ? (1, 0) : (0, 1)
if visited[parent] && !visited[child] {
visited[child] = true
DFS(curSheep + nextState.0, curWolf + nextState.1)
visited[child] = false
}
}
}
return total
}