[LeetCode] 0752. Open the Lock open wheel lock

topic

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

The lock initially starts at '0000', a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

Do you have a turntable with four circular dial lock. Each dial has 10 digits: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. Each dial may rotate freely: for example, the '9' to '0', '0' to '9'. Each rotation can only rotate the dial of a digit.

Lock initial number is '0000', a number of the dial string represents four.

Deadends list contains a set number of deaths, the same number and once any element in the list click wheel, the lock will be permanently locked and can no longer be rotated.

String target representatives can unlock digital, you need to give the minimum number of rotations, if any case can not unlock, returns -1.

Example 1:

Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output: 6
Explanation:
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102".

Example 2:

Input: deadends = ["8888"], target = "0009"
Output: 1
Explanation:
We can turn the last wheel in reverse to move from "0000" -> "0009".

Example 3:

Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
Output: -1
Explanation:
We can't reach the target without getting stuck.

Example 4:

Input: deadends = ["0000"], target = "8888"
Output: -1

Note:

The length of deadends will be in the range [1, 500].
target will not be in the list deadends.
Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'.

A Solution

Ideas: BFS is a simple title search, the point to note is that each time you search, first through all the elements in the queue, all finished to do a second round of search processing. There is a queue and when traversing a modified first size to survive, otherwise it will get the wrong results.

Inadequate: I do not know why the speed and memory usage are so big, one character may be operating directly in mobile computing, with no effect to the quick int, on the one hand visted use unordered_set<string>, efficiency and memory is certainly not bool visited[10000]+ memset(visited, 0, sizeof(visited))to good.

Re-brush leetcode the next day, the first to achieve such a practice your hand, then do it to improve performance.

class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        unordered_set<string> deadset(deadends.begin(), deadends.end());
        if (deadset.count("0000")) {
            return -1;
        }
        queue<string> q;
        unordered_set<string> visited;
        q.push("0000");
        visited.insert("0000");

        int result = 0;
        // 开始BFS搜索
        while (!q.empty()) {
            result++;
            auto size = q.size();
            for (int i = 0; i < size; i++) {
                string seq = q.front();
                q.pop();
                // 获取所有有效移动
                auto moves = getValidMoves(seq);
                for (auto& move : moves) {
                    if (move == target) {
                        return result;
                    }
                    // 如果该移动不是deadend且没访问过,则入队
                    if (!deadset.count(move) && !visited.count(move)) {
                        q.push(move);
                        visited.insert(move);
                    }
                    // 如果是deadend则不做处理,相当于绕过deadend
                }
            }

        }
        // 没有找到目标序列,返回-1
        return -1;
    }

    vector<string> getValidMoves(const string& sequence) {
        vector<string> moves;
        for (int i = 0; i < 4; i++) {
            string temp = sequence;
            // +1
            temp[i] = temp[i] == '9' ? '0' : temp[i] + 1;
            moves.push_back(temp);
            // -1
            temp = sequence;
            temp[i] = temp[i] == '0' ? '9' : temp[i] - 1;
            moves.push_back(temp);
        }
        return moves;
    }
};

operation result:

Runtime: 324 ms, faster than 27.97% of C++ online submissions for Open the Lock.
Memory Usage: 106.9 MB, less than 17.31% of C++ online submissions for Open the Lock.

Solution two

It can be said on the fantastic, first carefully observed topics, can be found the following:

  • Destination Unreachable condition is, deadends there must be only one more step and target sequence (for example deadends = "8888", target = "8889"), that is, it can be seen directly from the deadends whether the target up;
  • All direct calculation results up to (target the previous step) The required steps, and calculates the smallest step can be, do not need to use BFS;

This algorithm really be luck ah ~

class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        unordered_set<string> deadset(deadends.begin(), deadends.end());
        if (deadset.count("0000") || deadset.count(target)) {
            return -1;
        }
        vector<string> movesToTarget;
        auto moves = getValidMoves(target);
        for (auto& move : moves) {
            if (!deadset.count(move)) {
                movesToTarget.push_back(move);
            }
        }
        // 可以直接从deadends中看出target可不可达
        if (movesToTarget.empty()) {
            return -1;
        }
        // 最大步长是40步(每位转动10次)
        int min_stride = 40;
        // 计算到达每个可达结果的步长,取最小
        for (auto& move : movesToTarget) {
            int cur_stride = 0;
            for (int i = 0; i < 4; ++i) {
                int turns = move[i] - '0';
                // 可以倒着转,所以转动次数不会大过5
                if (turns > 5) {
                    turns = 10 - turns;
                }
                cur_stride += turns;
            }
            if (cur_stride < min_stride) {
                min_stride = cur_stride;
            }
        }
        // 最后加上到达target的那一步
        return min_stride + 1;
    }

    vector<string> getValidMoves(const string& sequence) {
        vector<string> moves;
        for (int i = 0; i < 4; i++) {
            string temp = sequence;
            // +1
            temp[i] = temp[i] == '9' ? '0' : temp[i] + 1;
            moves.push_back(temp);
            // -1
            temp = sequence;
            temp[i] = temp[i] == '0' ? '9' : temp[i] - 1;
            moves.push_back(temp);
        }
        return moves;
    }
};

operation result:

Runtime: 8 ms, faster than 100.00% of C++ online submissions for Open the Lock.
Memory Usage: 10.3 MB, less than 98.08% of C++ online submissions for Open the Lock.

Guess you like

Origin www.cnblogs.com/bingmang/p/11408331.html