begin에서 target이 될 때까지 DFS탐색을 하면서 총 몇 번에 변환이 완료되는지 구하면 된다.
단어는 오직 한 글자씩만 변할 수 있으니 반복문을 통해서 각각 단어들을 비교해주고
차이가 1이라면 DFS를 재귀 호출해주면 된다.
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
|
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool vis[51];
int ans = 100000;
void DFS(string cur, string target, vector<string> ar, int cnt, int n, int sum) {
if (cur == target) {
ans = min(ans, sum);
}
if (cnt == n) return;
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
vis[i] = true;
int tmp = 0;
for (int j = 0; j < ar[i].size(); ++j) {
if (ar[i][j] != cur[j]) ++tmp;
}
if (tmp == 1) DFS(ar[i], target, ar, cnt + 1, n, sum + 1);
vis[i] = false;
}
}
}
int solution(string begin, string target, vector<string> words) {
int answer = 0;
DFS(begin, target, words, 0, words.size(), 0);
return ans == 100000 ? 0 : ans;
}
|
cs |
'Programmers' 카테고리의 다른 글
프로그래머스 실패율 (0) | 2020.12.26 |
---|---|
프로그래머스 기능개발 (0) | 2020.12.11 |
[프로그래머스 C++] 카카오프렌즈 컬러링북 (0) | 2020.09.28 |
[프로그래머스 C++] 소수 찾기 (0) | 2020.09.27 |
[프로그래머스 C++] 완주하지 못한 선수 (0) | 2020.09.26 |