Check if a cell can be visited more than once in a String in C++

Suppose we have a string with dots (.) and a number, a dot indicates the cell is empty, and if there is a number x in any cell, it indicates that we can move x steps to the right or left within the string. Our task is to check whether we can visit a cell more than once or not. For example, if a string is like "2 . . . 2 . .", then we can visit 4th cell in two different ways. From second cell to two step to right, or from two step left from cell 6.

We will use one array called visited[] to keep track of the number of times ith cell of the string can be visited. Now traverse the string, and check if the current character is dot, or a number. For dot, do nothing, for x, increase the number, and increase the count of visits in the visited array within the range [i - x, i + x] by 1. By traversing visited array, if we get some room is visited more than one time or not.

Example

#include <iostream>
#include <string>
#include <vector>
using namespace std;

bool canVisitCellMoreThanOnce(string s) {
   int n = s.length();
   vector<int> visited(n, 0);
   
   for (int i = 0; i < n; i++) {
      if (s[i] != '.') {
         int x = s[i] - '0';
         // Mark cells that can be reached from position i
         for (int j = max(0, i - x); j <= min(n - 1, i + x); j++) {
            visited[j]++;
         }
      }
   }
   
   // Check if any cell is visited more than once
   for (int i = 0; i < n; i++) {
      if (visited[i] > 1) {
         return true;
      }
   }
   
   return false;
}

int main() {
   string s = "2...2..";
   
   if (canVisitCellMoreThanOnce(s))
      cout << "Yes, we can visit a cell more than once" << endl;
   else
      cout << "No, we cannot visit any cell more than once" << endl;
   
   return 0;
}

Output

Yes, we can visit a cell more than once
Updated on: 2019-10-22T10:58:43+05:30

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements