알고리즘 문제/Programmers
단어 변환
parkit
2019. 5. 3. 20:45
728x90
반응형
https://programmers.co.kr/learn/courses/30/lessons/43163
기본적인 백트래킹 문제이다.
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #include <iostream> #include <deque> #include <list> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> #include <map> #include <set> #pragma warning(disable:4996) #pragma comment(linker, "/STACK:336777216") using namespace std; bool use[51] = { false, }; int MIN = 0; bool check(string s, string g) { int other = 0; for (int i = 0; i < s.length(); i++) if (s.at(i) != g.at(i)) { ++other; if (other >= 2) return false; } return true; } void simulation(string begin, string target, vector<string> words, int cnt) { if (begin == target) { MIN = min(MIN, cnt); return; } for (int i = 0; i < words.size(); i++) if (!use[i] && check(begin, words.at(i))) { use[i] = true; simulation(words.at(i), target, words, cnt + 1); use[i] = false; } } int solution(string begin, string target, vector<string> words) { int answer = 0; MIN = 2e9; simulation(begin, target, words, 0); answer = MIN; if (answer == 2e9) answer = 0; return answer; } int main(void) { string begin, target; vector<string> words = { "hot", "dot", "dog", "lot", "log", "cog" }; begin = "hit"; target = "cog"; cout << solution(begin, target, words) << '\n'; return 0; } | cs |
728x90
반응형