[프로그래머스] 단어 변환

2019. 10. 30. 05:45알고리즘

 

 

코딩테스트 연습 - 단어 변환 | 프로그래머스

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다. 2. words에 있는 단어로만 변환할 수 있습니다. 예를 들어 begin이 hit, target가 cog, words가 [hot,dot,dog,lot,log,cog]라면 hit -> hot -> dot -> dog ->

programmers.co.kr

문제 설명

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

입출력 예 설명

예제 #1
문제에 나온 예와 같습니다.

예제 #2
target인 cog는 words 안에 없기 때문에 변환할 수 없습니다.

 

 

-

 

begin 부터 시작해서 그 다음 단어가 될 수 있는 string이 있는지 찾는 방식으로 문제를 풀었습니다. 현재 상태에서 한 글자만 다른 string으로 진행을 할 수 있기 때문에 queue를 이용해서 BFS로 문제를 풀었습니다. 

string과 현재까지의 count를 queue에 담고, next를 검사하는 방식으로 문제를 풀었고, BFS이므로 최단거리임이 보장되어 target과 현재 string이 같다면 바로 count + 1을 return 해 줍니다.

 

#include <string>
#include <vector>
#include <queue>

using namespace std;

bool isChangeable(string temp, string next) {
    int count = 0;
    int length = temp.size();
    
    for (int i = 0; i < length; i++) {
        count += (temp[i] != next[i] ? 1 : 0);
        if (count > 1) return false;
    }
    return true;
}

int solution(string begin, string target, vector<string> words) {
    int answer = 0;
    int size = words.size();
    
    vector<bool> isVisited(size);
    queue<pair<string, int> > q;
    
    q.push(pair<string, int>(begin, 0));
    while (!q.empty()) {
        string temp = q.front().first;
        int tempCount = q.front().second;
        q.pop();
        
        for (int i = 0; i < size; i++) {
            if (!isVisited[i] && isChangeable(temp, words[i])) {
                if (words[i] == target) {
                    answer = tempCount + 1;
                    return answer;
                }
                
                isVisited[i] = true;
                q.push(pair<string, int>(words[i], tempCount + 1));
            }
        }
    }
    
    return answer;
}

 

'알고리즘' 카테고리의 다른 글

[LeetCode] Permutations  (0) 2019.12.23
[LeetCode] Binary Tree Inorder Traversal  (0) 2019.12.21
[백준] 11493번: 이항 계수 5  (0) 2019.08.02
[백준] 10830번: 행렬 제곱  (0) 2019.07.26
[백준] 1016번: 제곱 ㄴㄴ 수  (0) 2019.07.26