forked from algorithm023/algorithm023
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathladderLength.cpp
More file actions
49 lines (46 loc) · 1.43 KB
/
Copy pathladderLength.cpp
File metadata and controls
49 lines (46 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <vector>
#include <queue>
#include <unordered_set>
#include <iostream>
using namespace std;
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
//데蕨BFS
unordered_set<string> bank, visited;//痰set속醵꿴冷
for (int i = 0; i < wordList.size(); i++) {
bank.insert(wordList[i]);
}
if (bank.find(endWord) == bank.end())return 0;
queue<string> recordBegin;
recordBegin.push(beginWord);
int nSize = 0;
int level = 1;//痙커雷鋼관벵菱
string strTmp;
while (!recordBegin.empty()) {
nSize = recordBegin.size();
while (nSize--) {
strTmp = recordBegin.front();
recordBegin.pop();
for (int j = 0; j < strTmp.size(); j++) {
char ch = strTmp[j];
for (int i = 0; i < 26; i++) {//殮쌈俚캡競뻣
char chNew = i + 'a';
if (strTmp[j] == chNew) continue;
strTmp[j] = chNew;
if (strTmp == endWord) return ++level;
if (bank.find(strTmp) != bank.end()) {
recordBegin.push(strTmp);
bank.erase(strTmp);
}
}
strTmp[j] = ch;
}
}
++level;
}
return 0;
}
//void main()
//{
// vector<string> bank = { "hot", "dot", "dog", "lot", "log"};
// ladderLength("hit", "cog", bank);
//}