๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Programmers][DFS/BFS] ๋‹จ์–ด ๋ณ€ํ™˜

ibelieveinme 2023. 5. 7. 16:11
728x90

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

 

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

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

programmers.co.kr

 

[ํ•ด๊ฒฐ์ฑ…]

๋‹จ์–ด๊ฐ€ 1๊ฐœ ์ฐจ์ด๋‚˜๋Š” ๋‹จ์–ด๋ฅผ ์ฐพ์•„์„œ BFS๋ฅผ ๊ณ„์† ๋Œ๋ฆฐ๋‹ค.

์ด๋•Œ ํƒ์ƒ‰ count๋ฅผ ๊ณ„์† ์ฒดํฌํ•ด๊ฐ€๋ฉฐ ์ตœ์†Œ count๊ฐ’์„ ๊ตฌํ•ด์•ผ ํ•œ๋‹ค.

์ข…๋ฃŒ์กฐ๊ฑด์€ ํƒ์ƒ‰ ๋‹จ์–ด๋ฅผ ์ฐพ์•˜์„ ๋•Œ์™€ words๋ฐฐ์—ด ๋์— ๋„๋‹ฌํ–ˆ์Œ์—๋„ target๋‹จ์–ด๋ฅผ ๋ชป๋งŒ๋‚ฌ์„ ๊ฒฝ์šฐ๋‹ค.

 

[์•Œ์•„๋‘˜ ๊ฒƒ]

1) INT_MAX๋Š” limits.h๋ฅผ ์„ ์–ธํ•ด์ค˜์•ผ ํ•œ๋‹ค.

2) ์žฌํƒ์ƒ‰์„ ์œ„ํ•ด ๋ฐฉ๋ฌธ์ฒดํฌ ํ–ˆ๋‹ค๊ฐ€ ํ’€์–ด์ฃผ๋Š” ๋ถ€๋ถ„.

 

[์ฝ”๋“œ]

#include <string>
#include <vector>
#include <iostream>
#include <limits.h>
using namespace std;

int answer = INT_MAX;

int DFS(string begin, string target, vector<string> words, vector<bool> &isVisited, int searchCount){

    //searchCount๊ฐ€ answer๋ณด๋‹ค ํฌ๋ฉด ํƒ์ƒ‰ ํ•„์š” ์—†์Œ
    if(searchCount > answer) return answer;
    
    //ํƒ์ƒ‰ํ•˜๋Š” ๋‹จ์–ด๊ฐ€ target์ด๋ž‘ ๊ฐ™์œผ๋ฉด answer ๊ฐ’ ์—…๋ฐ์ดํŠธํ•˜๊ณ  return
    if(begin == target){
        answer = searchCount;
        cout << answer << " ";
        return answer;
    }

    //๋‹จ์–ด๊ฐœ์ˆ˜๋งŒํผ ๋ฐ˜๋ณตํ•˜๋ฉฐ ๋‹จ์–ด ํ•˜๋‚˜์”ฉ ์„ ํƒ
    //๋ฐฉ๋ฌธํ•œ์  ์—†๋Š” ๋‹จ์–ด์„ ํƒ 
    for(int i = 0; i < words.size(); i++){
        if(isVisited[i]) continue;

        //๋‹จ์–ด 1๊ฐœ ์ฐจ์ด๋‚˜๋Š”์ง€ ์ฒดํฌ
        int diffCount = 0;
        for(int j = 0; j < words[i].length(); j++){
            if(begin[j] != words[i][j]) diffCount++;            
        }
        
        if(diffCount == 1){
            cout << words[i] << " ";
            //๋ฐฉ๋ฌธ์ฒดํฌ   
            isVisited[i] = true;
            DFS(words[i], target, words, isVisited, searchCount+1);
            //์žฌ๋ฐฉ๋ฌธ์„ ์œ„ํ•ด ๋ฐฉ๋ฌธ์ฒดํฌ ํ•ด์ œ
            isVisited[i] = false;
        }
    } 
    return answer;
}

int solution(string begin, string target, vector<string> words) {
    vector<bool> isVisited(words.size(), false);
    answer = DFS(begin, target, words, isVisited, 0);
    return (answer == INT_MAX) ? 0 : answer; 
}

 

728x90