본문 바로가기

알고리즘/Programmers

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

단어 변환[BFS/DFS]

두 개의 단어 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 안에 없기 때문에 변환할 수 없습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <string>
#include <vector>
#include<queue>
#include<iostream>
using namespace std;
queue<pair<string,int>> q; //begin값과 cnt
int cnt=0;
bool visited[51];
 
int solution(string beginstring target, vector<string> words) {
    int answer = 0;
    
    //target이 words배열안에 없는 경우
    int num=0;
    for(int i=0; i<words.size();i++){
        if(target==words[i])num++;
    }
    if(num==0)return 0;
    
    q.push({begin,0});
    //cout<<"출력";
    while(!q.empty())
    {
        string s = q.front().first;
        int cnt = q.front().second;
        q.pop();
        //타겟이랑 일치하면
        if(s==target)return cnt;
        
        //문자열 검색
        for(int i=0; i<words.size();i++){
            int ans=0;
            //이미 방문했으면 pass
            if(visited[i])continue;
            for(int j=0; j<words[i].size();j++){
                //한개의 알파벳만 달라야함
                if(s[j]!=words[i].at(j)) ans++;
                if(ans>1)break;
            }
            
            if(ans>1)continue;
            else{
                visited[i]=true;
                q.push({words[i],cnt+1});
            }
 
        }
    }    
 
    return answer;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter




|본 포스팅은 쿠팡 파트너스의 일환으로 소정의 수수료를 제공받을 수 있음을 알립니다 |