๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค (๋‹จ์–ด ๋ณ€ํ™˜, ๊นŠ์ด/๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰(DFS/BFS)) C++

by UKHYUN22 2021. 12. 30.
728x90

 

DFS๊ฐ€ ์•„๋‹ˆ๋ผ BFS ์ธ๊ฒƒ ๊ฐ™๊ธดํ•œ๋ฐ ์ผ๋‹จ ํ•จ์ˆ˜๋ช…์€ ์ด๋ ‡๊ฒŒ dfs๋กœ ํ•ด๋ฒ„๋ ธ๋‹ค. ์•„๋‹Œ๊ฐ€... ์•„์ง ๊ฐœ๋…์ด ํ™•์‹คํžˆ ์žกํžˆ์ง„ ์•Š์€๋“ฏ.. ์•„๋ฌดํŠผ DFS์™€ BFS๋ฅผ ํ•  ๋•Œ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ํ•˜๋‚˜์”ฉ ๋ฐ”๋€Œ์–ด์„œ ๋„˜๊ฒจ์ง€๊ฒŒ ๋˜๋Š” ๊ฒƒ์— Focus๋ฅผ ๋งž์ถ˜๋‹ค. ๊ทธ๋ฆฌ๊ณ  visited๊ฐ€ ๊ฐ€์žฅ ์ค‘์š”!! ๊ทธ๋ฆฌ๊ณ  ์ด ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ์˜ node๋ฅผ queue์— ๋ชจ๋‘ ๋„ฃ๊ณ  ์‚ดํ”ผ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— dfs ์žฌ๊ท€๋ฅผ ํƒˆ์ถœํ•˜๊ฒŒ ๋˜๋ฉด ์ด์ค‘ for๋ฌธ ์ค‘ nested๋œ for๋ฌธ์—์„œ visited ํ•œ ๋…ธ๋“œ์˜ visited๋ฅผ 0์œผ๋กœ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์ด ํฌ์ธํŠธ

 

 

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int answer = 100;
string value;
vector<int> visited(50,0);

void dfs(string begin, string target, vector<string> words, int result) {
    
    if(begin == target) {
        if(answer > result) answer = result;
        return ;
    }
    
    // word ๋ฐฐ์—ด์— ๋“ค์–ด์žˆ๋Š” ๊ฐœ์ˆ˜๋งŒํผ ๋ฐ˜๋ณต
    for(int i = 0 ; i < words.size() ; i++) {
        // count ๋ณ€์ˆ˜๋Š” for๋ฌธ์„ ๋Œ ๋•Œ๋งˆ๋‹ค ์ดˆ๊ธฐํ™”๋ฅผ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.
        int count = 0;
        
        // words ๋ฐฐ์—ด์˜ ๋‹จ์–ด ํฌ๊ธฐ๋งŒํผ ๋ฐ˜๋ณต์„ ํ•˜๋ฉด์„œ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์ค€๋‹ค.
        for(int j = 0 ; j < words[i].size() ; j++) {
            if(begin[j] != words[i][j]) count++;
        }
        
        // ํ‹€๋ฆฐ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๊ฐ€ 1๊ฐœ์ด๋ฉด DFS๋ฅผ ์‹ค์‹œํ•œ๋‹ค.
        if(count == 1) {
            // ๋งŒ์•ฝ ํ•ด๋‹น ๋‹จ์–ด๋ฅผ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜์œผ๋ฉด
            if(visited[i] == 0) {
                // ๋ฐฉ๋ฌธ์„ ํ•˜๊ณ 
                visited[i] = 1;
                // DFS๋ฅผ ์ง„ํ–‰ํ•œ๋‹ค.
                dfs(words[i], target, words, result+1);
                /* 
                DFS๋ฅผ ํƒˆ์ถœํ–ˆ๋‹ค๋Š” ๊ฒƒ์€ begin == target์˜ ์ƒํ™ฉ์„ ๋งŒ๋‚ฌ๊ณ  
                ํ•ด๋‹น answer์— result ๊ฐ’์„ ๋„ฃ์—ˆ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.
                ์ด๋ฅผ ๋‹ค์‹œ 0์œผ๋กœ ๋ฐ”๊พธ๋Š” ์ด์œ ๋Š” ์ด์ „ begin์—์„œ Spell ์ด 1๊ฐœ๊ฐ€ ๋‹ค๋ฅธ ๋‹จ์–ด๊ฐ€
                ์—ฌ๋Ÿฌ ๊ฐœ ์กด์žฌํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ•ด๋‹นํ•˜๋Š” ๋‹จ์–ด๋กœ๋„ ๋ฐ”๋€” ์ˆ˜ ์žˆ์–ด์•ผ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ
                ํƒ์ƒ‰ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
                */
                visited[i] = 0;
            }
        }
    }
}

int solution(string begin, string target, vector<string> words) {

    dfs(begin, target, words, 0);
    
    // ๋งŒ์•ฝ answer๊ฐ€ 100์ด๋ฉด result๊ฐ€ ๋ฐ”๋€Œ์ง€ ์•Š์•˜๋‹ค๋Š” ๊ฒƒ์ด๊ณ  ๋ฐ”๋€” ์ˆ˜ ์—†๋‹ค๋Š” ๊ฒƒ
    if(answer == 100) answer = 0;
    
    return answer;
}