Find the count of unvisited indices in an infinite array | Java 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
import java . util . LinkedList ; import java . util . Queue ; class GFG { public static int countUnvisited ( int n , int m ) { int X = ( m * n ) - m - n ; Queue < Integer > queue = new LinkedList < > ( ) ; queue . add ( X ) ; int count = 0 ; while ( ! queue . isEmpty ( ) ) { int curr = queue . poll ( ) ; count ++ ; if ( curr - m > 0 ) queue . add ( curr - m ) ; if ( curr - n > 0 ) queue . add ( curr - n ) ; } return count ; } public static void main ( String args [ ] ) { int n = 2 , m = 5 ; System . out . print ( countUnvisited ( n , m ) ) ; } }