BFS中的最小步数模型
因为只有四个数字,因此将四位字符串转换成数字,判断和变化都是对数字进行的
const int N = 10010;
class Solution {
public:
bool stop[N];
int dist[N];
bool visited[N];
int d[4];
int turn(int s, int n, int dir) {
if (!dir) dir = -1; // +1 right, -1 left
for (int i = 0; i < 4; i++) d[i] = s % 10, s = s / 10;
d[n] = (d[n] + dir + 10) % 10;
int ans = 0;
for (int i = 3; i >= 0; i--) ans = (ans * 10) + d[i];
return ans;
}
int openLock(vector<string>& deadends, string target) {
for (auto s : deadends) stop[stoi(s)] = true;
int end = stoi(target);
memset(dist, 0x3f, sizeof dist);
memset(visited, 0, sizeof visited);
queue<int> q;
q.push(0);
visited[0] = true;
dist[0] = 0;
while (q.size()) {
auto t = q.front(); q.pop();
if (stop[t]) continue;
if (t == end)
return dist[t];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 2; j++) {
int ne = turn(t, i, j);
if (stop[ne]) continue;
if (visited[ne]) continue;
q.push(ne);
dist[ne] = dist[t] + 1;
visited[ne] = true;
}
}
return -1;
}
};