Minimum time required to fill given N slots | Java program for the above approach ; Function to return the minimum time to fill all the slots ; Stores visited slots ; Checks if a slot is visited or not ; Insert all filled slots ; Iterate until queue is not empty ; Iterate through all slots in the queue ; Front index ; If previous slot is present and not visited ; If next slot is present and not visited ; Increment the time at each level ; Print the answer ; Driver Code ; Function Call
import java . io . * ; import java . util . * ; class GFG { public static void minTime ( int arr [ ] , int N , int K ) { Queue < Integer > q = new LinkedList < > ( ) ; boolean vis [ ] = new boolean [ N + 1 ] ; int time = 0 ; for ( int i = 0 ; i < K ; i ++ ) { q . add ( arr [ i ] ) ; vis [ arr [ i ] ] = true ; } while ( q . size ( ) > 0 ) { for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int curr = q . poll ( ) ; if ( curr - 1 >= 1 && ! vis [ curr - 1 ] ) { vis [ curr - 1 ] = true ; q . add ( curr - 1 ) ; } if ( curr + 1 <= N && ! vis [ curr + 1 ] ) { vis [ curr + 1 ] = true ; q . add ( curr + 1 ) ; } } time ++ ; } System . out . println ( time - 1 ) ; } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = { 2 , 6 } ; int K = arr . length ; minTime ( arr , N , K ) ; } }