Algorithm

[Programmers] 단어 변환

0so0 2023. 9. 4. 19:00
728x90
반응형
SMALL

프로그래머스 단어 변환 C++ 풀이 정리

SMALL


단어 변환

문제 

두 개의 단어 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

 

풀이

아래 세가지를 고려해서 dfs로 풀면됨

1. 모든 단어에 대해서 한글자만 다른지 비교

2. 모든 경우의 수를 판단해야 하기 때문에 dfs 수행 후 방문처리 초기화 필요

3. dfs를 수행할때마다 depth를 하나 증가 시켜서 전달

전체 코드

더보기
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

// 최소값은 최대 단어 개수인 50개로 초기화
int answer = 50;
bool visited[50];

// 한글자만 다른지 비교하는 함수
bool charcompare(string a, string b) {
    int cnt = 0;

    // 문자 비교
    for (int i = 0; i < a.size(); i++) {
        if (a[i] != b[i]) cnt++;
    }

    // 다른게 한글자면 true return
    if (cnt == 1) return true;
    return false;
}

void dfs(string begin, string target, vector<string>words, int depth) {
    // begin과 target이 같을 경우 변환 완료로 최소값 갱신
    if (begin == target) {
        answer = min(answer, depth);
        return;
    }

    // 모든 단어 비교
    for (int i = 0; i < words.size(); i++) {
        // 한글자만 다르고, 방문하지 않았을경우
        if (charcompare(begin, words[i]) && !visited[i]) {
            // 방문 처리
            visited[i] = true;
            // depth를 한단계 증가하여 전달
            dfs(words[i], target, words, depth + 1);
            // 백트래킹을 위해 초기화
            visited[i] = false;
        }
    }

    return;
}

int solution(string begin, string target, vector<string> words) {
    // begin을 target으로 변환시키기 위해 dfs 수행
    dfs(begin, target, words, 0);

    // answer이 초기값인 경우 변환 실패로 0 return
    if (answer == 50)
        return 0;

    return answer;
}

 

728x90
반응형
LIST

'Algorithm' 카테고리의 다른 글

[BAEKJOON] 11724 연결 요소의 개수  (0) 2023.08.24
[Programmers] 타겟 넘버  (0) 2023.08.23
[BAEKJOON] 3190 뱀  (0) 2023.08.17
[BAEKJOON] 18406 럭키 스트레이트  (0) 2023.08.14
[BAEKJOON] 1439 뒤집기  (0) 2023.08.14