[프로그래머스] 여행경로
const solution = (ticketsArray) => {
const tickets = {}
let answer = null
ticketsArray.forEach((ticket) => {
if (tickets[ticket[0]]) {
tickets[ticket[0]].push(ticket[1])
} else {
tickets[ticket[0]] = [ticket[1]]
}
})
Object.values(tickets).map((ticket) => ticket.sort())
const getTicketCount = (tickets) =>
Object.values(tickets).reduce((prev, curr) => prev + curr.length, 0)
const dfs = (now, tickets, route) => {
const newRoute = [...route, now]
const destinations = tickets[now]
if (answer) return
if (getTicketCount(tickets) === 0) {
answer = newRoute
return
}
if (!destinations || !destinations.length) return
destinations.map((destination, idx) => {
let copiedTickets = JSON.parse(JSON.stringify(tickets))
copiedTickets[now].splice(idx, 1)
dfs(destination, copiedTickets, newRoute)
})
}
dfs('ICN', tickets, [])
return answer
}