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
52
53
54
#include <string>
#include <vector>
 
using namespace std;
 
int answer = 51;
bool visit[51= {false};
 
void DFS(string begin, string target, vector<string>& words, int result, int& answer) 
{
    if (begin == target)
    {
        if (answer > result)
            answer = result;
 
        return;
    }
 
    for (int i = 0; i < words.size(); ++i) 
    {
        int iCount = 0;
    
        for (int j = 0; j < words[i].size(); ++j) 
        {
            if (begin[j] != words[i][j]) 
                ++iCount;
        
            if (iCount == 2)
                break;
        }
 
        if (iCount == 1)
        {
            if (!visit[i])
            {
                visit[i] = true;
               DFS(words[i], target, words, result + 1, answer);
                visit[i] = false;
            }
        }
    }
}
 
int solution(string begin, string target, vector<string> words)
{
    int answer = 51;
 
    dfs(begin, target, words, 0, answer);
 
    if (answer == 51)
        return 0;
 
    return answer;
}
cs

1. 두 개 넘게 차이날 때 들어가지 않는 것

2. visit을 걸었다가 취소하는 것

이 두 개가 중요하다. 최대가 50개이기 때문에 최대만 안넘으면 된다

+ Recent posts