본문 바로가기
전공공부/코딩테스트

프로그래머스 dfs/bfs 단어변환

by 시아나 2021. 9. 10.

문제 설명

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.


1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다.
2. words에 있는 단어로만 변환할 수 있습니다.

예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면

"hit" -> "hot" -> "dot" -> "dog" -> "cog" 와 같이 4단계를 거쳐 변환할 수 있습니다.

두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.

제한사항

  • 각 단어는 알파벳 소문자로만 이루어져 있습니다.
  • 각 단어의 길이는 3 이상 10 이하이며 모든 단어의 길이는 같습니다.
  • words에는 3개 이상 50개 이하의 단어가 있으며 중복되는 단어는 없습니다.
  • begin과 target은 같지 않습니다.
  • 변환할 수 없는 경우에는 0를 return 합니다.

입출력 예

begin target words return
"hit" "cog" ["hot", "dot", "dog", "lot", "log", "cog"] 4
"hit" "cog" ["hot", "dot", "dog", "lot", "log"] 0

정답코드

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

using namespace std;    
int answer = 0;

bool check(string n1, string n2) { //단어의 차가 1인 단어를 찾는 하무
    int count = 0;
    for (int i = 0; i < n1.size(); i++) {
        if (n1[i] != n2[i]) count++;
    }
    if (count == 1) return true;
    else return false;
}

void dfs(string start, string target, bool visited[200], vector<string> words, int count) {
    if (start == target) { //target과 일치하면 반환
        answer = count;
        return;
    }
    for (int i = 0; i < words.size(); i++) { //모든 경우의 수를 도는 동작
        if (!visited[i] && check(start, words[i])) {
            visited[i] = true; //방문함을 표시함
            dfs(words[i],target,visited, words, count + 1);
            visited[i] = false; //재귀에서 돌아왔는 경우 : 해당 경우의 수가 아니라는 뜻이므로 방문을 취소함
        }
    }
}

int solution(string begin, string target, vector<string> words) {
    bool visited[200] = { false };
    if (find(words.begin(), words.end(), target) == words.end()) return 0; //target이 없는 경우
    dfs(begin,target,visited, words, 0);
    return answer;
}

처음 내 코드

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

using namespace std;    
int answer = 0;

bool check(string n1, string n2) {
    int count = 0;
    for (int i = 0; i < n1.size(); i++) {
        if (n1[i] != n2[i]) count++;
    }
    if (count == 1) return true;
    else return false;
}

int dfs(string start,int index, string target, bool visited[200], vector<string> words, int count) {
    if (start == target) {
        answer = count;
        return -1;
    }
    if (index != -1) visited[index] = true;
    for (int i = 0; i < words.size(); i++) {
        if (!visited[i] && check(start, words[i])) {
            count = dfs(words[i],i, target,visited, words, count + 1);
            if (count == -1) return -1;
        }
    }
    return count-1;
}

int solution(string begin, string target, vector<string> words) {
    bool visited[200] = { false };
    if (find(words.begin(), words.end(), target) == words.end()) return 0;
    dfs(begin, -1, target,visited, words, -1);
    return answer;
}

 

문제원인 : 재귀함수를 사용함에 있어 발생되는 동작순서에 대한 이해가 부족했다.

count를 올리고 낮추는 부분, visited를 check하고 헤제하는 부분의 코드가 잘못 됬었다.