Java Program to Find Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings

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 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:
 

Java




// Java Program to count the minimum
// number of circular rotations required
// to obtain a given numeric Strings
// avoiding a set of blocked Strings
import 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


Output: 

12

 



Contact Us