-
[프로그래머스] DFS/BFS(3) 단어 변환알고리즘/알고리즘 풀이 2020. 1. 28. 18:42
문제 설명
두 개의 단어 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 풀이
#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; vector<int> ans; void dfs(string begin, string target, vector<string> words, string history, int n) { for (int i = 0; i < words.size(); i++) { cout << i << endl; cout << history << endl; string word = words[i]; string tmp = word; //탐색 가능한 단어 구하기 int same = 0; for (int j = 0; j < begin.size(); j++) { for (int k = 0; k < word.size(); k++) { if (begin[j] == tmp[k]) { tmp[k] = '.'; //중복체크 방지 same++; break; } } } //1개 알파벳만 다른경우 if (same == begin.size()-1) { //탐색 가능한 단어가 일전에 탐색한 단어인지 체크(새로운 단어인 경우만 탐색) if (history.find(word) == string::npos) { if (target == word) {//타켓을 구하면, 탐색 횟수를 저장한다. ans.push_back(n+1); // cout << n+1 << endl; return; } //begin은 다음 탐색 단어!, 탐색시 탐색 횟수 증가(n+1) dfs(word, target, words, history + " " + word, n + 1); } } } } int solution(string begin, string target, vector<string> words) { int answer = 0; dfs(begin, target, words, begin, 0); if (!ans.empty()) { sort(ans.begin(), ans.end()); answer = ans[0]; } return answer; }
해당 문제 링크
https://programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환 | 프로그래머스
두 개의 단어 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
'알고리즘 > 알고리즘 풀이' 카테고리의 다른 글
[프로그래머스] Hash(2) 전화번호 목록 (0) 2020.01.29 [프로그래머스] DP(7) 서울에서 경산까지 (0) 2020.01.23 [프로그래머스] DP(6) 도둑질 (0) 2020.01.20 댓글