본문 바로가기

프로그래머스/DFS 와 BFS

여행경로

728x90

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

#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

bool find(vector<bool>&check,vector<vector<string>> &tickets, int idx, vector<string>&route){
    
    string goal = tickets[idx][1];
    route.push_back(goal);
    if(route.size()==tickets.size()+1){return true;}

    for(int i=0; i<tickets.size(); i++){
        if((tickets[i][0]==goal)&&(check[i]==false)){
            check[i]=true;
            if(find(check,tickets,i,route)){return true;};
            check[i]=false;
        }
    }
    route.pop_back();
    return false;
}

vector<string> solution(vector<vector<string>> tickets) {
    
    vector<string> answer;
    vector<string> route;
    
    sort(tickets.begin(),tickets.end());
    for(int i=0; i<tickets.size(); i++){
        vector<bool>check(tickets.size(),false);
        if(tickets[i][0]=="ICN"){
            check[i]=true;
            route.push_back("ICN");
           if(find(check,tickets,i,route)==true)break;
            route.clear();
        }
    }
    answer = route;
    return answer;
}

 

 

'프로그래머스 > DFS 와 BFS' 카테고리의 다른 글

단어변환  (0) 2021.02.08
네트워크  (0) 2021.02.05
BFS & DFS  (0) 2021.01.25
쿼드압축 후 개수세기  (0) 2021.01.12
타겟넘버  (0) 2021.01.06