백준 2668_ swift

hankyulee·2021년 12월 4일
0

Swift coding test 준비

목록 보기
46/57

dfs 가 왜 필요한지 말해주는 문제.
내일부터 dfs 공부하자!
var n = Int(readLine()!)!
var array = Int
array.append(0)
for _ in 0 ..< n {
array.append(Int(readLine()!)!)
}
let count = array.count - 1
var resultArray = Int
var result = 0

func function( array : [Int], index : Int, target : Int, resultArray : [Int]) -> [Int] {
var resultArray = resultArray
if array[index] == target {
result += 1
resultArray.append(index)
return resultArray
}
else {
if resultArray.contains(index) {return []}
resultArray.append(index)
//print("1 index :",index)
result += 1
let newIndex = array[index]
//print("i= ",newIndex)

    return function(array, newIndex, target, resultArray)
}

}

for i in (1 ... count) {
if array[i] >= i {
//print("start:",i)
let result = function(array, i, i, [])
//print("i,r",i,result)
resultArray = resultArray + result
//print(array[i],i)
}
}
let resultSet = Set(resultArray).sorted()
print(resultSet.count)
for r in resultSet{
print(r)
}

0개의 댓글