๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Programmers][DFS/BFS] ์—ฌํ–‰๊ฒฝ๋กœ

ibelieveinme 2023. 5. 9. 05:16
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/43164

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

์ฃผ์–ด์ง„ ํ•ญ๊ณตํŽธ์„ ๋ชจ๋‘ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ๋กœ๋ฅผ ์ฐพ์œผ๋ฉด ๋œ๋‹ค. ๊ฒฝ๋กœ๊ฐ€ ์—ฌ๋Ÿฌ๊ฐœ๋ฉด ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๊ฐ€ ๋น ๋ฅธ ๊ฒฝ๋กœ ํ•œ๊ฐœ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 

 

*ํ•ด๊ฒฐ๋ฒ•

์ฃผ์–ด์ง„ ํ•ญ๊ณตํŽธ์„ ๋ชจ๋‘ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋ฏ€๋กœ, ICN๋ถ€ํ„ฐ ์ถœ๋ฐœ์ง€์  -> ๋„์ฐฉ์ง€์ ์„ DFS๋กœ ํƒ์ƒ‰ํ–ˆ๋‹ค.

์ด ๋•Œ, ๊ฒฝ๋กœ๋ฅผ ์ €์žฅํ•ด์•ผ ํ•˜๋ฏ€๋กœ answer ๋Š” stack(vector) ํ›„์ž…์„ ์ถœ ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

 

๊ตฌ์ฒด์ ์ธ ๋ฐฉ๋ฒ•์€ ์ถœ๋ฐœ์ง€์ ์œผ๋กœ ์ง€์ •ํ•œ ๋ฌธ์ž์™€ ๊ฐ™์€๊ฑธ ์ฐพ๊ณ , ๋„์ฐฉ์ง€์ ์„ ๋‹ค์‹œ ์ถœ๋ฐœ์ง€์ ์œผ๋กœ ์„ค์ •ํ•˜๋ฉฐ ๋ชจ๋“  ํ•ญ๊ณตํŽธ์„ ๋‹ค ์‚ฌ์šฉํ•  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฉด ๋œ๋‹ค. DFS ํƒ์ƒ‰์‹œ depth ๋ฅผ ๊ฐ™์ด ๋ณด๋‚ด์„œ ์ตœ์†Œ depth ์ธ์ง€๋ฅผ ํŒ๋‹จํ•ด์•ผ ํ•œ๋‹ค.

 

 

*์•Œ์•„๋‘˜ ๊ฒƒ

1) ๋ฒกํ„ฐ ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™”

vector<bool> isVisited(tickets.size(), false);

2) vector ๊ฐ’ ๋„ฃ๊ณ  ๋นผ๊ธฐ

answer.push_back(airport);

answer.pop_back();

 

 

*์ฝ”๋“œ

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

bool DFS(string airport, vector<vector<string>> tickets, vector<string> &answer, vector<bool> &isVisited, int ticketCount){
    answer.push_back(airport);
    if(ticketCount == tickets.size()) return true;
    
    for(int i = 0; i < tickets.size(); i++){
        if(tickets[i][0] == airport && !isVisited[i]){
            isVisited[i] = true;
            if(DFS(tickets[i][1], tickets, answer, isVisited, ticketCount + 1)){
                return true;
            }
            isVisited[i] = false;
        }
    }
    answer.pop_back();
    return false;
}

vector<string> solution(vector<vector<string>> tickets) {
    vector<string> answer;
    vector<bool> isVisited(tickets.size(), false);
    
    //๊ฐ€๋Šฅํ•œ ๊ฒฝ๋กœ๊ฐ€ 2๊ฐœ ์ด์ƒ์ผ ๋•Œ ์•ŒํŒŒ๋ฒณ ์ˆœ์„œ๊ฐ€ ์•ž์„œ๋Š” ๊ฒฝ๋กœ๋ฅผ return ํ•ด์•ผ ํ•˜๋ฏ€๋กœ ๋ฏธ๋ฆฌ ์ •๋ ฌ.
    sort(tickets.begin(), tickets.end());
    //DFS ํƒ์ƒ‰์œผ๋กœ ๋ชจ๋‘ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒฝ๋กœ ์ฐพ๊ธฐ
    DFS("ICN", tickets, answer, isVisited, 0);
    
    return answer;
}

 

728x90