링크 : programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수
programmers.co.kr
분류 : 깊이/너비 우선 탐색 (DFS/BFS)
#include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(string begin, string target, vector<string> words) {
int answer = 0;
queue<pair<string,int>> q;
q.push(make_pair(begin,0));
while(!q.empty()){
string s1 = q.front().first;
int num = q.front().second;
q.pop();
if(s1==target){
return num;
}
for(int i=0; i<words.size(); i++){
int cnt = 0;
for(int j=0; j<words[i].size(); j++){
if(s1[j]==words[i][j]) cnt++;
}
if(cnt==words[i].size()-1){
q.push(make_pair(words[i],num+1));
words[i] = "";
}
}
}
return answer;
}
전형적인 BFS문제로, 큐의 쌍을 만드는 법만 잘 활용하면 문제없이 풀 수 있다.
'🖥️ CS > SW Expert 외의 Algorithms' 카테고리의 다른 글
(프로그래머스 C++) Lv2 카펫 (1) | 2020.10.14 |
---|---|
(프로그래머스 C++) Lv3 여행경로 (0) | 2020.10.14 |
(프로그래머스 C++) Lv2 문제 중 문자열 (1) (0) | 2020.10.13 |
(프로그래머스 C++) 네트워크 (0) | 2020.10.03 |
(프로그래머스 C++) 타겟 넘버 (0) | 2020.10.03 |