Check if a cell can be visited more than once in a String
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++
#include <bits/stdc++.h>
using namespace std;
bool checkIfOverlap(string str)
{
int len = str.length();
int visited[len + 1] = { 0 };
for ( int i = 0; i < len; i++) {
if (str[i] == '.' )
continue ;
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 (visited[i] > 1) {
return true ;
}
}
return false ;
}
int main()
{
string str = ".2..2." ;
if (checkIfOverlap(str))
cout << "YES" ;
else
cout << "NO" ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static boolean checkIfOverlap(String str)
{
int len = str.length();
int []visited = new int [len + 1 ];
for ( int i = 0 ; i < len; i++) {
if (str.charAt(i)== '.' )
continue ;
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 (visited[i] > 1 ) {
return true ;
}
}
return false ;
}
public static void main (String[] args) {
String str = ".2..2." ;
if (checkIfOverlap(str))
System.out.println( "YES" );
else
System.out.print( "NO" );
}
}
|
Python 3
def checkIfOverlap( str ) :
length = len ( str )
visited = [ 0 ] * (length + 1 )
for i in range (length) :
if str [i] = = "." :
continue
for j in range ( max ( 0 , i - ord ( str [i]),
min (length, i +
ord ( str [i])) + 1 )) :
visited[j] + = 1
for i in range (length) :
if visited[i] > 1 :
return True
return False
if __name__ = = "__main__" :
str = ".2..2."
if checkIfOverlap( str ) :
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
class GFG
{
static bool checkIfOverlap(String str)
{
int len = str.Length;
int [] visited = new int [len + 1];
for ( int i = 0; i < len; i++)
{
if (str[i]== '.' )
continue ;
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 (visited[i] > 1)
{
return true ;
}
}
return false ;
}
public static void Main ()
{
String str = ".2..2." ;
if (checkIfOverlap(str))
Console.Write( "YES" );
else
Console.Write( "NO" );
}
}
|
PHP
<?php
function checkIfOverlap( $str )
{
$len = strlen ( $str );
$visited = array_fill (0, $len + 1, NULL);
for ( $i = 0; $i < $len ; $i ++)
{
if ( $str [ $i ] == '.' )
continue ;
for ( $j = max(0, $i - $str [ $i ]);
$j <= min( $len , $i + $str [ $i ]);
$j ++)
$visited [ $j ]++;
}
for ( $i = 0; $i < $len ; $i ++)
{
if ( $visited [ $i ] > 1)
{
return true;
}
}
return false;
}
$str = ".2..2." ;
if (checkIfOverlap( $str ))
echo "YES" ;
else
echo "NO" ;
?>
|
Javascript
<script>
function checkIfOverlap(str)
{
let len = str.length;
let visited = new Array(len +1);
for (let i=0;i<visited.length;i++)
{
visited[i]=0;
}
for (let i = 0; i < len; i++) {
if (str[i]== '.' )
continue ;
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 (visited[i] > 1) {
return true ;
}
}
return false ;
}
let str = ".2..2." ;
if (checkIfOverlap(str))
document.write( "YES" );
else
document.write( "NO" );
</script>
|
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" ;
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
{
static boolean isCellVisitable(String path)
{
Set<String> visitedCells = new HashSet<>();
String currentPosition = "0,0" ;
visitedCells.add(currentPosition);
for ( int i = 0 ; i < path.length(); i++) {
char move = path.charAt(i);
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 );
}
if (visitedCells.contains(currentPosition))
{
return true ;
}
visitedCells.add(currentPosition);
}
return false ;
}
public static void main(String[] args)
{
String path = "UDLR" ;
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
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
path = "UDLR"
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" ;
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 isCellVisitable(path) {
const visitedCells = new Set();
let currentPosition = [0, 0];
visitedCells.add(currentPosition);
for (const move of path) {
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];
}
if (visitedCells.has(currentPosition)) {
return true ;
}
visitedCells.add(currentPosition);
}
return false ;
}
const path = 'UDLR' ;
if (isCellVisitable(path)) {
console.log( 'The cell can be visited more than once' );
} else {
console.log( 'The cell can be visited only once' );
}
|
OutputThe cell can be visited more than once
time complexity :O(n)
space complexity :O(n)
Last Updated :
08 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...