Skip to content
Rain Hu's Workspace
Go back

[Algo] 2-1. 暴力演算法 Brute Force

Rain Hu

一、暴力演算法


二、暴力演算法應用

1. 數組

2. 樹

tree

3. 圖論

graph

三、例題

string plus(string s, int i) {
    if (s[i] == '9') {
        s[i] = '0';
    } else {
        s[i]++;
    }
    return s;
}
string minus(string s, int i) {
    if (s[i] == '0') {
        s[i] = '9';
    } else {
        s[i]--;
    }
    return s;
}
int openLock(vector<string>& deadends, string target) {
    unordered_set<string> set(deadends.begin(), deadends.end());
    string start = "0000";
    if (set.count(start)) return -1;
    queue<string> q;
    q.push(start);
    int step = 0;
    while (!q.empty()) {
        int sz = q.size();
        while (sz--) {
            string curr = q.front();
            q.pop();
            if (curr == target) return step;
            for (int i = 0; i < 4; i++) {
                string next;
                next = plus(curr, i);
                if (!set.count(next)) q.push(next);
                set.insert(next);
                next = minus(curr, i);
                if (!set.count(next)) q.push(next);
                set.insert(next);
            }   
        }
        step++;
    }

    return -1;
}


Share this post on:

Previous
[Algo] 2-2. 貪心演算法 Greedy
Next
[LeetCode] 491. Non-decreasing Subsequences