Minimum time to reach from Node 1 to N if travel is allowed only when node is Green | Import library for Queue ; Function to find min edge ; Initialize queue and push [ 1 , 0 ] ; Create visited array to keep the track if node is visited or not ; Run infinite loop ; If node is N , terminate loop ; Travel adjacent nodes of crnt ; Check whether we visited previously or not ; Push into queue and make as true ; Function to Find time required to reach 1 to N ; Check color of node is red or green ; Add C sec from next green color time ; Add C ; Return the answer ; Driver Code ; Given Input ; Function Call ; Print total time
from queue import Queue NEW_LINE def minEdge ( ) : NEW_LINE INDENT Q = Queue ( ) NEW_LINE Q . put ( [ 1 , 0 ] ) NEW_LINE V = [ False for _ in range ( N + 1 ) ] NEW_LINE while 1 : NEW_LINE INDENT crnt , c = Q . get ( ) NEW_LINE if crnt == N : NEW_LINE INDENT break NEW_LINE DEDENT for _ in X [ crnt ] : NEW_LINE INDENT if not V [ _ ] : NEW_LINE INDENT Q . put ( [ _ , c + 1 ] ) NEW_LINE V [ _ ] = True NEW_LINE DEDENT DEDENT DEDENT return c NEW_LINE DEDENT def findTime ( c ) : NEW_LINE INDENT ans = 0 NEW_LINE for _ in range ( c ) : NEW_LINE INDENT if ( ans // T ) % 2 : NEW_LINE INDENT ans = ( ans // T + 1 ) * T + C NEW_LINE DEDENT else : NEW_LINE INDENT ans += C NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE M = 5 NEW_LINE T = 3 NEW_LINE C = 5 NEW_LINE X = [ [ ] , [ 2 , 3 , 4 ] , [ 4 , 5 ] , [ 1 ] , [ 1 , 2 ] , [ 2 ] ] NEW_LINE c = minEdge ( ) NEW_LINE ans = findTime ( c ) NEW_LINE print ( ans ) NEW_LINE DEDENT