[프로그래머스] 여행경로 (자바스크립트/javascript/js)

2021. 6. 28. 13:08Front-end/알고리즘

728x90
반응형

문제출처: https://programmers.co.kr/learn/courses/30/lessons/43164

 

코딩테스트 연습 - 여행경로

[["ICN", "SFO"], ["ICN", "ATL"], ["SFO", "ATL"], ["ATL", "ICN"], ["ATL","SFO"]] ["ICN", "ATL", "ICN", "SFO", "ATL", "SFO"]

programmers.co.kr

 

내가 작성한 코드

function solution(tickets) {
  const answer = [];
  const DFS = (start, tickets, path) => {
    const newPath = [...path, start];
    if (tickets.length === 0) {
      answer.push(path);
    } else {
      tickets.map((ticket, index) => {
        if (ticket[0] === start) {
          const copiedTickets = [...tickets];
          const nextAirport = ticket[1];
          copiedTickets.splice(index, 1);
          DFS(nextAirport, copiedTickets, newPath);
        }
      });
    }
    DFS("ICN", tickets, []);
    return answer.sort()[0];
  };
}
const tickets = [
  ["ICN", "SFO"],
  ["ICN", "ATL"],
  ["SFO", "ATL"],
  ["ATL", "ICN"],
  ["ATL", "SFO"],
];
console.log(solution(tickets));
728x90
반응형