Find the count of unvisited indices in an infinite array | C ++ implementation of the approach ; Function to return the count of unvisited indices starting from the index 0 ; Largest index that cannot be visited ; Push the index to the queue ; To store the required count ; Current index that cannot be visited ; Increment the count for the current index ; ( curr - m ) and ( curr - n ) are also unreachable if they are valid indices ; Return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countUnvisited ( int n , int m ) { int X = ( m * n ) - m - n ; queue < int > queue ; queue . push ( X ) ; int count = 0 ; while ( queue . size ( ) > 0 ) { int curr = queue . front ( ) ; queue . pop ( ) ; count ++ ; if ( curr - m > 0 ) queue . push ( curr - m ) ; if ( curr - n > 0 ) queue . push ( curr - n ) ; } return count ; } int main ( ) { int n = 2 , m = 5 ; cout << countUnvisited ( n , m ) ; return 0 ; }