Minimum time required to fill given N slots | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minTime ( vector < int > arr , int N , int K ) { queue < int > q ; vector < bool > vis ( N + 1 , false ) ; int time = 0 ; for ( int i = 0 ; i < K ; i ++ ) { q . push ( arr [ i ] ) ; vis [ arr [ i ] ] = true ; } while ( q . size ( ) > 0 ) { for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int curr = q . front ( ) ; q . pop ( ) ; if ( curr - 1 >= 1 && ! vis [ curr - 1 ] ) { vis [ curr - 1 ] = true ; q . push ( curr - 1 ) ; } if ( curr + 1 <= N && ! vis [ curr + 1 ] ) { vis [ curr + 1 ] = true ; q . push ( curr + 1 ) ; } } time ++ ; } cout << ( time - 1 ) ; } int main ( ) { int N = 6 ; vector < int > arr = { 2 , 6 } ; int K = arr . size ( ) ; minTime ( arr , N , K ) ; }