pranay_teja
11/13/2018 - 10:46 AM

LeetCode-OpenTheLock

#include<bits/stdc++.h>
using namespace std;

// #LeetCode #Graphs #BFS
// https://leetcode.com/explore/learn/card/queue-stack/231/practical-application-queue/1375/
// https://www.youtube.com/watch?v=M7GgV6TJTdc
// 4
// 5
// 0201
// 0101
// 0102
// 1212
// 2002
// 0202
// 1
// 8888
// 0009
// 8
// 8887
// 8889
// 8878
// 8898
// 8788
// 8988
// 7888
// 9888
// 8888
// 1
// 0000
// 8888

// 6
// 1
// -1
// -1

void inc(char &c){
    c= ( ( (c-'0') +1) %10 )+'0';
}
void dec(char &c){
    if(c=='0'){
        c='9';
    }else{
        c=( ( (c-'0') -1) %10 )+'0';
    }
}

int openLock(vector<string>& deadends, string target) {
    map<string,bool> visited;
    for(int i=0;i<deadends.size();i++){
        visited[deadends[i]]=true; // mark as visited so we dont visit them in BFS
    }
    int steps=0;
    string init="0000";
    queue<string> Q;
    if(init==target){
        return 0; // no turns reqd
    }
    if(visited[init]!=true){
        Q.push(init);
    }else{
        return -1; // if starting comb is a deadend
    }
    visited[init]=true; // mark starting combination as visited
    while(!Q.empty()){
        steps++;
        int levelSize=Q.size();
        for(int j=0;j<levelSize;j++){ // loop for same level elements
            string curr=Q.front(); // add all possible comb's from current level front
            for(int i=0;i<4;i++){ // generate all possible comb's
                string tempInc=curr;
                string tempDec=curr;
                inc(tempInc[i]);
                dec(tempDec[i]);
                if(visited[tempInc]!=true){
                    if(tempInc==target){
                        return steps; // turns reqd
                    }
                    Q.push(tempInc);
                    visited[tempInc]=true;
                }
                if(visited[tempDec]!=true){
                    if(tempDec==target){
                        return steps; // turns reqd
                    }
                    Q.push(tempDec);
                    visited[tempDec]=true;
                }
            }
            Q.pop();
        }
    }
    return -1;
}

int main(){
    freopen("ip.txt","r",stdin);
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        vector<string> deadends(n);
        for(int i=0;i<n;i++){
            cin>>deadends[i];
        }
        string target;
        cin>>target;
        cout<<openLock(deadends,target)<<endl;
    }
    return 0;
}