Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings - GeeksforGeeks

15 Feb, 2021
Given a numeric string target of length N and a set of numeric strings blocked, each of length N, the task is to find the minimum number of circular rotations required to convert an initial string consisting of only 0‘s to target by avoiding any of the strings present in blocked at any step. If not possible, print -1.Note: A single rotation involves increasing or decreasing a value at particular index by 1 unit. As rotations are circular, 0 can be converted to 9 or a 9 can be converted to 0.Examples:  
Input: target = “7531”, blocked = {“1543”, “7434”, “7300”, “7321”, “2427” } Output: 12 Explanation: “0000” -> “9000” -> “8000” -> “7000” -> “7100” -> “7200” -> “7210” -> “7310” -> “7410” -> “7510” -> “7520” -> “7530” -> “7531”Input: target = “4231”, blocked = { “1243”, “4444”, “1256”, “5321”, “2222” } Output: 10  
 
Approach: In order to solve this problem, we are using the following BFS approach:  
Create a string start of length N consisting of only 0’s. Push it to queue. The queue is created to store the next valid combination possible by increasing or decreasing a character by an unit.
Create an unordered set avoid, and add all the blocked strings in it.
If start or target is present in avoid, the required target cannot be reached.
Pop start from queue and traverse all the characters of start. Increase and decrease each character by an unit keeping the remaining constant and check if the string is present in avoid. If not and the new combination is not equal to target, push it to the queue and insert into avoid to prevent repeating the same combination in future.
Once the entire length of start is traversed, repeat the above steps for the next level, which are the the valid strings obtained from start and are currently present in the queue.
Keep repeating the above steps until target is reached or there are no further combinations left and the queue has become empty.
At any instant, if the string formed is equal to target, return the value of count which keeps a count of the number of levels of BFS traversals. The value of count is the minimum number of circular rotations required.
If no further state can be obtained and the queue is empty, print “Not Possible”.
Below is the implementation of the above logic: 
C++
Java
// C++ Program to count the minimum// number of circular rotations required// to obtain a given numeric strings// avoiding a set of blocked strings #include <bits/stdc++.h>using namespace std; int minCircularRotations(    string target,    vector<string>& blocked,    int N){    string start = "";    for (int i = 0; i < N; i++) {        start += '0';    }     unordered_set<string> avoid;     for (int i = 0; i < blocked.size(); i++)        avoid.insert(blocked[i]);     // If the starting string needs    // to be avoided    if (avoid.find(start) != avoid.end())        return -1;     // If the final string needs    // to be avoided    if (avoid.find(target) != avoid.end())        return -1;     queue<string> qu;    qu.push(start);     // Variable to store count of rotations    int count = 0;     // BFS Approach    while (!qu.empty()) {         count++;         // Store the current size        // of the queue        int size = qu.size();         for (int j = 0; j < size; j++) {             string st = qu.front();            qu.pop();             // Traverse the string            for (int i = 0; i < N; i++) {                 char ch = st[i];                 // Increase the                // current character                st[i]++;                 // Circular rotation                if (st[i] > '9')                    st[i] = '0';                 // If target is reached                if (st == target)                    return count;                 // If the string formed                // is not one to be avoided                if (avoid.find(st)                    == avoid.end())                    qu.push(st);                 // Add it to the list of                // strings to be avoided                // to prevent visiting                // already visited states                avoid.insert(st);                 // Decrease the current                // value by 1 and repeat                // the similar checkings                st[i] = ch - 1;                 if (st[i] < '0')                    st[i] = '9';                if (st == target)                    return count;                if (avoid.find(st)                    == avoid.end())                    qu.push(st);                avoid.insert(st);                 // Restore the original                // character                st[i] = ch;            }        }    }     return -1;} // Driver codeint main(){    int N = 4;    string target = "7531";    vector<string> blocked        = { "1543",            "7434",            "7300",            "7321",            "2427" };     cout << minCircularRotations(                target,                blocked, N)         << endl;     return 0;}
// Java Program to count the minimum// number of circular rotations required// to obtain a given numeric Strings// avoiding a set of blocked Stringsimport java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.LinkedList;import java.util.Queue; class GFG{  static int minCircularRotations(String target,                                  ArrayList<String> blocked,                                  int N)  {    String start = "";    for (int i = 0; i < N; i++)    {      start += '0';    }     HashSet<String> avoid = new HashSet<>();    for (int i = 0; i < blocked.size(); i++)      avoid.add(blocked.get(i));     // If the starting String needs // to be avoided    if (avoid.contains(start))      return -1;     // If the final String needs // to be avoided    if (avoid.contains(target))      return -1;    Queue<String> qu = new LinkedList<>();    qu.add(start);     // Variable to store count of rotations    int count = 0;     // BFS Approach    while (!qu.isEmpty())    {      count++;       // Store the current size // of the queue      int size = qu.size();      for (int j = 0; j < size; j++)      {        StringBuilder st = new StringBuilder(qu.poll());         // Traverse the String        for (int i = 0; i < N; i++)        {          char ch = st.charAt(i);           // Increase the // current character          st.setCharAt(i, (char) (st.charAt(i) + 1));           // Circular rotation          if (st.charAt(i) > '9')            st.setCharAt(i, '0');           // If target is reached          if (st.toString().equals(target))            return count;           // If the String formed          // is not one to be avoided          if (!avoid.contains(st.toString()))            qu.add(st.toString());           // Add it to the list of          // Strings to be avoided          // to prevent visiting          // already visited states          avoid.add(st.toString());           // Decrease the current          // value by 1 and repeat          // the similar checkings          st.setCharAt(i, (char) (ch - 1));          if (st.charAt(i) < '0')            st.setCharAt(i, '9');          if (st.toString().equals(target))            return count;          if (!avoid.contains(st.toString()))            qu.add(st.toString());          avoid.add(st.toString());           // Restore the original          // character          st.setCharAt(i, ch);        }      }    }    return -1;  }   // Driver code  public static void main(String[] args)  {    int N = 4;    String target = "7531";    ArrayList<String> blocked =      new ArrayList<>(Arrays.asList("1543",                                    "7434",                                    "7300",                                    "7321",                                    "2427"));    System.out.println(minCircularRotations(target, blocked, N));  }} // This code is contributed by sanjeev2552
12
 
sanjeev2552
BFS
rotation
Competitive Programming
Mathematical
Queue
Strings
Strings
Mathematical
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers