-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordChange.cpp
More file actions
42 lines (33 loc) · 756 Bytes
/
wordChange.cpp
File metadata and controls
42 lines (33 loc) · 756 Bytes
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
#include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(string begin, string target, vector<string> words) {
int answer = 0;
int wordsNum = words.size();
int wordCnt = begin.size();
vector<int> visit(wordsNum, 0);
queue<pair<string, int>> qu;
qu.push({ begin, 0 });
int diff;
while (!qu.empty()) {
string start = qu.front().first;
int count = qu.front().second;
qu.pop();
for (int i = 0; i < wordsNum; i++) {
diff = 0;
if (visit[i] != 0) continue;
for (int j = 0; j < wordCnt; j++) {
if (start[j] != words[i][j])
diff++;
}
if (diff == 1) {
if (words[i] == target)
return count + 1;
visit[i] = 1;
qu.push({ words[i], count + 1 });
}
}
}
return answer;
}