프로그래머스 - 단어 변환

seio·2022년 10월 31일
0

coding study

목록 보기
11/12
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <iostream>
using namespace std;

int solution(string begin, string target, vector<string> words) {
    int answer = 0;
    
    //words 가 넘게 바꾸지 못한 경우는 답이 없다.
    
    // 단어 길이는 3~10이며 모든 단어는 길이가 같다.
    map<string,bool> mp; // 시간? // 배열 사용해도 됨. visited[n]
    
    for(auto iter:words){
        mp[iter]=false;
    }
    
    queue<pair<string,int>> q;
    q.push(make_pair(begin,0)); // 단어와 이동 숫자
    
    while(!q.empty()){
        string tmp = q.front().first;
        int cnt = q.front().second;
        cout<<tmp<<endl;
        
        q.pop();
        
        if(target == tmp){
            answer = cnt;
            break;
        }
        
        // 모두 방문하면 탈출
        // if(cnt>words.size()){
        //    answer = 0;
        //    break;
        // }
        
        for(int i = 0 ;i<words.size();i++){
            int differ_cnt=0;
            
            if(mp[words[i]])
                continue;
            
            for(int j =0;j<tmp.size();j++){
                if(tmp[j]!=words[i][j])
                    differ_cnt++;
            }
            if(differ_cnt==1){
                //cout<<"judge: "<<words[i]<<endl;
                q.push(make_pair(words[i],cnt+1));
                mp[words[i]]=true;
            }
        }
    }
    
    
    
    return answer;
}
profile
personal study area

0개의 댓글