[プログラマー]単語を変換(c++)
[プログラマー]単語を変換(c++)
質問へのアクセス
これはdfsの問題です.
現在のwordとwordsの単語を選択して比較し、1つのアルファベットだけが異なる場合は変更して次のステップに進みます.
ノードをブラウズするたびに、現在のwordがtargetと一致するかどうかを求めることができます.
コード実装(C++)
#include <string>
#include <vector>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
int check[51];
int result = 987654321;
bool oneAlphaDif(string str1 ,string str2){
int cnt = 0;
for(int i = 0 ; i < str1.length() ; i++){
if(str1[i] != str2[i]) cnt++;
}
if(cnt == 1) return true;
else return false;
}
void dfs(int cnt, string word, string target, vector<string> words){
if(word == target){
result = min(result, cnt);
}
else{
for(int i = 0 ; i < words.size() ; i++){
if(!check[i] && oneAlphaDif(word, words[i])){
check[i] = true;
dfs(cnt + 1, words[i], target, words);
check[i] = false;
}
}
}
}
int solution(string begin, string target, vector<string> words) {
int answer = 0;
memset(check, false, sizeof(check));
dfs(0, begin, target, words);
if(result == 987654321) result = 0;
answer = result;
return answer;
}
Reference
この問題について([プログラマー]単語を変換(c++)), 我々は、より多くの情報をここで見つけました https://velog.io/@kpg0518/프로그래머스-단어-변환cテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol