File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ struct si {
4+ string s;
5+ int steps;
6+ };
7+ string rotate (string s, int i, int dir) {
8+ s[i] = (((s[i] - ' 0' ) + dir + 10 ) % 10 ) + ' 0' ;
9+ return s;
10+ }
11+ int openLock (vector<string>& deadends, string target) {
12+ // bfs with graph, which consist of 10000 nodes.
13+ // each node has 8 neighbors.
14+ queue<si> q;
15+ vector<int > dirs = {-1 , 1 };
16+
17+ unordered_set<string> dead;
18+ for (auto &s : deadends) {
19+ dead.insert (s);
20+ }
21+
22+ if (dead.count (" 0000" ) <= 0 )
23+ q.push (si (
24+ " 0000" ,
25+ 0
26+ ));
27+
28+ unordered_set<string> found;
29+ found.insert (" 0000" );
30+
31+ bool is_valid = false ;
32+ int ret = std::numeric_limits<int >::max ();
33+
34+ while (!q.empty ()) {
35+ auto top = q.front ();
36+ q.pop ();
37+
38+ if (top.s == target) {
39+ return top.steps ;
40+ }
41+
42+ for (int i = 0 ; i < 4 ; ++i) {
43+ for (auto dir : dirs) {
44+ auto new_str = rotate (top.s , i, dir);
45+ if (dead.count (new_str) <= 0 && found.count (new_str) <= 0 ) {
46+ q.push (si (new_str, top.steps +1 ));
47+ found.insert (new_str);
48+ }
49+ }
50+ }
51+ }
52+
53+
54+ return -1 ;
55+ }
56+ };
You can’t perform that action at this time.
0 commit comments