Programmers/Level 3
[프로그래머스 3] 단어 변환 (C/C++)
워니-
2020. 1. 9. 03:54
#include <string> #include <vector> #include <queue> #include <map> using namespace std; vector<string> copy_words; string copy_target; queue<string> q; map<string, int> visited; int check(string word, string next) { int cnt = 0; for(int i = 0; i < word.size(); i++) { if(word[i] != next[i]) { cnt++; } } if(cnt == 1) { return 1; } else { return 0; } } void BFS(string begin) { visited[begin] = 1; q.push(begin); while(!q.empty()) { string word = q.front(); q.pop(); if(word == copy_target) { return; } for(int i = 0; i < copy_words.size(); i++) { if(check(word, copy_words[i]) == 1 && visited[copy_words[i]] == 0) { visited[copy_words[i]] = visited[word] + 1; q.push(copy_words[i]); } } } } int solution(string begin, string target, vector<string> words) { copy_words = words; copy_target = target; BFS(begin); if(visited[target] == 0) { return 0; } else { return visited[target]-1; } } | cs |