Skip to content

Commit 337a04d

Browse files
committed
AC 127, 运行时间有点慢
1 parent 0be8528 commit 337a04d

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed

P127.cpp

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include "header.h"
2+
#include <array>
3+
#include <bits/c++config.h>
4+
#include <cstddef>
5+
#include <cstring>
6+
#include <vector>
7+
8+
9+
#define LEN 5001
10+
class Solution {
11+
public:
12+
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
13+
array<bool, LEN> end;
14+
array<bool, LEN> visited;
15+
visited.fill(false);
16+
bool begin;
17+
bool hasEnd = false;
18+
end.fill(false);
19+
queue<pair<int, int>> q;
20+
for (size_t i=0; i<wordList.size(); i++) {
21+
if (transfer(beginWord, wordList[i])) begin = true;
22+
else begin=false;
23+
if (transfer(endWord, wordList[i])) end[i] = true;
24+
if (endWord == wordList[i]) hasEnd = true;
25+
if (begin) {
26+
q.emplace(i,2);
27+
visited[i] = true;
28+
}
29+
}
30+
if (!hasEnd) return 0;
31+
if (transfer(beginWord, endWord)) return 2;
32+
const size_t &n = wordList.size();
33+
static int map[LEN][LEN];
34+
for (size_t i=0; i<n; i++)
35+
map[i][0] = 0;
36+
for (size_t i=0; i<n; i++) {
37+
for (size_t j=i+1; j<n; j++) {
38+
if (transfer(wordList[i], wordList[j])) {
39+
map[i][++map[i][0]] = j;
40+
map[j][++map[j][0]] = i;
41+
}
42+
}
43+
}
44+
45+
while (!q.empty()) {
46+
int _last = q.front().first;
47+
int _step = q.front().second;
48+
if (end[_last]) {
49+
return _step+1;
50+
}
51+
52+
for (int i=1; i<=map[_last][0]; i++) {
53+
int j = map[_last][i];
54+
if (!visited[j]) {
55+
q.emplace(j, _step+1);
56+
visited[j] = true;
57+
}
58+
}
59+
q.pop();
60+
}
61+
return 0;
62+
}
63+
private:
64+
bool transfer(const string &a,const string &b) {
65+
int differ = 0;
66+
if (a.size()!=b.size()) return false;
67+
for (size_t i=0; i<a.size(); i++)
68+
if (a[i]!=b[i]) {
69+
differ++;
70+
if (differ>1) return false;
71+
}
72+
if (differ==1)
73+
return true;
74+
else
75+
return false;
76+
}
77+
};
78+
79+
int main() {
80+
string beginWord = "a";
81+
string endWord = "c";
82+
vector<string> wordList = {"a", "b", "c"};
83+
cout << Solution().ladderLength(beginWord, endWord, wordList) << endl;
84+
85+
return 0;
86+
}

header.h

+9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <array>
2+
#include <bits/c++config.h>
23
#include <cstdint>
34
#include<iostream>
45
#include<vector>
@@ -76,3 +77,11 @@ void print(vector<T> a) {
7677
cout << endl;
7778
return;
7879
}
80+
81+
template<typename T>
82+
void print(T a[], size_t n) {
83+
for (size_t i=0; i<n; i++)
84+
cout << a[i] << " ";
85+
cout << endl;
86+
return;
87+
}

0 commit comments

Comments
 (0)