Given a string which consists of either ‘.’ or any number. A ‘.’ in the string means that the cell is empty and if there is a number in any cell, it means one can move steps to right or left within the string.
The task is to check if any cell in the string can be visited more than once. If so, print YES otherwise print NO.
Examples:
Input : str = ".2...2.." Output: YES The fourth cell can be visited twice. One way to reach the fourth cell is from 2nd cell by moving 2 steps to right and another way to reach fourth cell is by moving 2 steps left from cell 6. Input : str = ".2...1" Output: NO None of the cells in the given string can be visited more than once.
The idea is to take an array visited[] to keep track of the number of times i-th cell of the string can be visited. Now traverse the string and check if the current character is a ‘.’ or a number . If the current character is a ‘.’ then do nothing otherwise if it is a number then increase the count of visits in the visited array within the range [i-x, i+x] by 1.
Finally, traverse the visited[] array and check if any cell is visited more than once.
Below is the implementation of the above approach:
C++
// C++ program to check if any cell of the // string can be visited more than once #include <bits/stdc++.h> using namespace std; // Function to check if any cell can be // visited more than once bool checkIfOverlap(string str) { int len = str.length(); // Array to mark cells int visited[len + 1] = { 0 }; // Traverse the string for ( int i = 0; i < len; i++) { if (str[i] == '.' ) continue ; // Increase the visit count of the left and right // cells within the array which can be visited for ( int j = max(0, i - str[i]); j <= min(len, i + str[i]); j++) visited[j]++; } for ( int i = 0; i < len; i++) { // If any cell can be visited more than once // Return True if (visited[i] > 1) { return true ; } } return false ; } // Driver code int main() { string str = ".2..2." ; if (checkIfOverlap(str)) cout << "YES" ; else cout << "NO" ; return 0; } |
Java
// Java program to check if any cell of the // string can be visited more than once import java.io.*; class GFG { // Function to check if any cell can be // visited more than once static boolean checkIfOverlap(String str) { int len = str.length(); // Array to mark cells int []visited = new int [len + 1 ]; // Traverse the string for ( int i = 0 ; i < len; i++) { if (str.charAt(i)== '.' ) continue ; // Increase the visit count of the left and right // cells within the array which can be visited for ( int j = Math.max( 0 , i - str.charAt(i)); j <= Math.min(len, i + str.charAt(i)); j++) visited[j]++; } for ( int i = 0 ; i < len; i++) { // If any cell can be visited more than once // Return True if (visited[i] > 1 ) { return true ; } } return false ; } // Driver code public static void main (String[] args) { String str = ".2..2." ; if (checkIfOverlap(str)) System.out.println( "YES" ); else System.out.print( "NO" ); } } // This code is contributed by inder_verma.. |
Python 3
# Python3 program to check if # any cell of the string can # be visited more than once # Function to check if any cell # can be visited more than once def checkIfOverlap( str ) : length = len ( str ) # Array to mark cells visited = [ 0 ] * (length + 1 ) # Traverse the string for i in range (length) : if str [i] = = "." : continue # Increase the visit count # of the left and right cells # within the array which can # be visited for j in range ( max ( 0 , i - ord ( str [i]), min (length, i + ord ( str [i])) + 1 )) : visited[j] + = 1 # If any cell can be visited # more than once, Return True for i in range (length) : if visited[i] > 1 : return True return False # Driver code if __name__ = = "__main__" : str = ".2..2." if checkIfOverlap( str ) : print ( "YES" ) else : print ( "NO" ) # This code is contributed # by ANKITRAI1 |
C#
// C# program to check if any // cell of the string can be // visited more than once using System; class GFG { // Function to check if any cell // can be visited more than once static bool checkIfOverlap(String str) { int len = str.Length; // Array to mark cells int [] visited = new int [len + 1]; // Traverse the string for ( int i = 0; i < len; i++) { if (str[i]== '.' ) continue ; // Increase the visit count of // the left and right cells // within the array which can be visited for ( int j = Math.Max(0, i - str[i]); j <= Math.Min(len, i + str[i]); j++) visited[j]++; } for ( int i = 0; i < len; i++) { // If any cell can be visited // more than once, Return True if (visited[i] > 1) { return true ; } } return false ; } // Driver code public static void Main () { String str = ".2..2." ; if (checkIfOverlap(str)) Console.Write( "YES" ); else Console.Write( "NO" ); } } // This code is contributed // by Akanksha Rai(Abby_akku) |
PHP
<?php // PHP program to check if any // cell of the string can be // visited more than once // Function to check if any cell // can be visited more than once function checkIfOverlap( $str ) { $len = strlen ( $str ); // Array to mark cells $visited = array_fill (0, $len + 1, NULL); // Traverse the string for ( $i = 0; $i < $len ; $i ++) { if ( $str [ $i ] == '.' ) continue ; // Increase the visit count of the // left and right cells within the // array which can be visited for ( $j = max(0, $i - $str [ $i ]); $j <= min( $len , $i + $str [ $i ]); $j ++) $visited [ $j ]++; } for ( $i = 0; $i < $len ; $i ++) { // If any cell can be visited // more than once, Return True if ( $visited [ $i ] > 1) { return true; } } return false; } // Driver code $str = ".2..2." ; if (checkIfOverlap( $str )) echo "YES" ; else echo "NO" ; // This code is contributed // by ChitraNayal ?> |
Javascript
<script> // JavaScript program to check if any cell of the // string can be visited more than once // Function to check if any cell can be // visited more than once function checkIfOverlap(str) { let len = str.length; // Array to mark cells let visited = new Array(len +1); for (let i=0;i<visited.length;i++) { visited[i]=0; } // Traverse the string for (let i = 0; i < len; i++) { if (str[i]== '.' ) continue ; // Increase the visit count of the left and right // cells within the array which can be visited for (let j = Math.max(0, i - str[i]); j <= Math.min(len, i + str[i]); j++) visited[j]++; } for (let i = 0; i < len; i++) { // If any cell can be visited more than once // Return True if (visited[i] > 1) { return true ; } } return false ; } // Driver code let str = ".2..2." ; if (checkIfOverlap(str)) document.write( "YES" ); else document.write( "NO" ); // This code is contributed by rag2127 </script> |
YES
Time Complexity: O(N2)
Space Complexity: O(N)
#using if-else in python:
In this program, we define a function called is_cell_visitable that takes a string representing a path as input and returns True if the cell can be visited more than once, and False otherwise.
The function works by maintaining a set of visited cells and the current position of the path. We add the current position to the set of visited cells and update the current position based on the direction of the move.
If the current position is already in the set of visited cells, then we return True, indicating that the cell can be visited more than once. If the entire path has been traversed and no cell has been visited more than once, then we return False.
Finally, we call the is_cell_visitable function with a sample path of “UDLR” and print whether the cell can be visited more than once or not using an if-else statement.
C++
#include <iostream> #include <set> #include <utility> using namespace std; bool is_cell_visitable(string path) { set<pair< int , int >> visited_cells; pair< int , int > current_position = make_pair(0, 0); visited_cells.insert(current_position); for ( char move : path) { if (move == 'U' ) { current_position = make_pair(current_position.first - 1, current_position.second); } else if (move == 'D' ) { current_position = make_pair(current_position.first + 1, current_position.second); } else if (move == 'L' ) { current_position = make_pair(current_position.first, current_position.second - 1); } else if (move == 'R' ) { current_position = make_pair(current_position.first, current_position.second + 1); } if (visited_cells.count(current_position) > 0) { return true ; } visited_cells.insert(current_position); } return false ; } int main() { string path = "UDLR" ; // Checking if the cell can be visited more than once if (is_cell_visitable(path)) { cout << "The cell can be visited more than once" << endl; } else { cout << "The cell can be visited only once" << endl; } return 0; } |
Java
import java.util.HashSet; import java.util.Set; public class Main { // Function to check if a cell can be visited more than // once given a path static boolean isCellVisitable(String path) { // Set to keep track of visited cells Set<String> visitedCells = new HashSet<>(); // Starting position is (0, 0) String currentPosition = "0,0" ; // Add starting position to visited cells set visitedCells.add(currentPosition); // Iterate over each move in the path for ( int i = 0 ; i < path.length(); i++) { char move = path.charAt(i); // Update current position based on move if (move == 'U' ) { currentPosition = (Integer.parseInt( currentPosition.split( "," )[ 0 ]) - 1 ) + "," + currentPosition.split( "," )[ 1 ]; } else if (move == 'D' ) { currentPosition = (Integer.parseInt( currentPosition.split( "," )[ 0 ]) + 1 ) + "," + currentPosition.split( "," )[ 1 ]; } else if (move == 'L' ) { currentPosition = currentPosition.split( "," )[ 0 ] + "," + (Integer.parseInt( currentPosition.split( "," )[ 1 ]) - 1 ); } else if (move == 'R' ) { currentPosition = currentPosition.split( "," )[ 0 ] + "," + (Integer.parseInt( currentPosition.split( "," )[ 1 ]) + 1 ); } // Check if current position has already been // visited if (visitedCells.contains(currentPosition)) { // Cell can be visited more than once return true ; } // Add current position to visited cells set visitedCells.add(currentPosition); } // Cell can be visited only once return false ; } // Driver code public static void main(String[] args) { String path = "UDLR" ; // Check if the cell can be visited more than once if (isCellVisitable(path)) { System.out.println( "The cell can be visited more than once" ); } else { System.out.println( "The cell can be visited only once" ); } } } |
Python3
# Cell Visitation Checker Function def is_cell_visitable(path): visited_cells = set () current_position = ( 0 , 0 ) visited_cells.add(current_position) for move in path: if move = = "U" : current_position = (current_position[ 0 ] - 1 , current_position[ 1 ]) elif move = = "D" : current_position = (current_position[ 0 ] + 1 , current_position[ 1 ]) elif move = = "L" : current_position = (current_position[ 0 ], current_position[ 1 ] - 1 ) elif move = = "R" : current_position = (current_position[ 0 ], current_position[ 1 ] + 1 ) if current_position in visited_cells: return True visited_cells.add(current_position) return False # Sample Input path = "UDLR" # Checking if the cell can be visited more than once if is_cell_visitable(path): print ( "The cell can be visited more than once" ) else : print ( "The cell can be visited only once" ) |
C#
using System; using System.Collections.Generic; class Program { static bool IsCellVisitable( string path) { var visitedCells = new HashSet<( int , int )>(); var currentPosition = (0, 0); visitedCells.Add(currentPosition); foreach ( var move in path) { switch (move) { case 'U' : currentPosition = (currentPosition.Item1 - 1, currentPosition.Item2); break ; case 'D' : currentPosition = (currentPosition.Item1 + 1, currentPosition.Item2); break ; case 'L' : currentPosition = (currentPosition.Item1, currentPosition.Item2 - 1); break ; case 'R' : currentPosition = (currentPosition.Item1, currentPosition.Item2 + 1); break ; } if (visitedCells.Contains(currentPosition)) { return true ; } visitedCells.Add(currentPosition); } return false ; } static void Main( string [] args) { var path = "UDLR" ; // Checking if the cell can be visited more than // once if (IsCellVisitable(path)) { Console.WriteLine( "The cell can be visited more than once" ); } else { Console.WriteLine( "The cell can be visited only once" ); } } } |
Javascript
// Function to check if a cell can be visited more than once given a path function isCellVisitable(path) { // Set to keep track of visited cells const visitedCells = new Set(); // Starting position is (0, 0) let currentPosition = [0, 0]; // Add starting position to visited cells set visitedCells.add(currentPosition); // Iterate over each move in the path for (const move of path) { // Update current position based on move if (move === 'U' ) { currentPosition = [currentPosition[0] - 1, currentPosition[1]]; } else if (move === 'D' ) { currentPosition = [currentPosition[0] + 1, currentPosition[1]]; } else if (move === 'L' ) { currentPosition = [currentPosition[0], currentPosition[1] - 1]; } else if (move === 'R' ) { currentPosition = [currentPosition[0], currentPosition[1] + 1]; } // Check if current position has already been visited if (visitedCells.has(currentPosition)) { // Cell can be visited more than once return true ; } // Add current position to visited cells set visitedCells.add(currentPosition); } // Cell can be visited only once return false ; } // Example usage const path = 'UDLR' ; // Check if the cell can be visited more than once if (isCellVisitable(path)) { console.log( 'The cell can be visited more than once' ); } else { console.log( 'The cell can be visited only once' ); } |
The cell can be visited more than once
time complexity :O(n)
space complexity :O(n)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!