human
Write me a code to minimum number of jumps to obtain an element of opposite parity and the other steps required given the following:
Minimum number of jumps to obtain an element of opposite parity | Bfs for odd numbers are source.
Initialize queue.
Stores for each node , the nodes visited and their distances.
If parity is 0 -> odd Otherwise -> even.
Perform multi - source bfs.
Extract the front element of the queue.
Traverse nodes connected to the current node.
If u is not visited.
If element with opposite parity is obtained.
Store its distance from source in ans [ ].
Push the current neighbour to the queue.
Function to find the minimum jumps required by each index to reach element of opposite parity.
Initialise Inverse Graph.
Stores the result for each index.
For the jumped index.
If the ind is valid then add reverse directed edge.
Multi - source bfs with odd numbers as source by passing 0.
Multi - source bfs with even numbers as source by passing 1.
Print the answer.
Driver Code"
How can the above be solved in Python?
assistant
#Here is code to minimum number of jumps to obtain an element of opposite parity and the other steps required.
 def bfs ( n , a , invGr , ans , parity ) :
	q = [ ]
	vis = [ 0 for i in range ( n + 1 ) ]
	dist = [ 0 for i in range ( n + 1 ) ]
	for i in range ( 1 , n + 1 ) :
		if ( ( a [ i ] + parity ) & 1 ) :
			q . append ( i )
			vis [ i ] = 1
	while ( len ( q ) != 0 ) :
		v = q [ 0 ]
		q . pop ( 0 )
		for u in invGr [ v ] :
			if ( not vis [ u ] ) :
				dist [ u ] = dist [ v ] + 1
				vis [ u ] = 1
				if ( ( a [ u ] + parity ) % 2 == 0 ) :
					if ( ans [ u ] == - 1 ) :
						ans [ u ] = dist [ u ]
				q . append ( u )
def minJumps ( a , jump , n ) :
	invGr = [ [ ] for i in range ( n + 1 ) ]
	ans = [ - 1 for i in range ( n + 1 ) ]
	for i in range ( 1 , n + 1 ) :
		for ind in [ i + jump [ i ] , i - jump [ i ] ] :
			if ( ind >= 1 and ind <= n ) :
				invGr [ ind ] . append ( i )
	bfs ( n , a , invGr , ans , 0 )
	bfs ( n , a , invGr , ans , 1 )
	for i in range ( 1 , n + 1 ) :
		print ( str ( ans [ i ] ) , end = ' ▁ ' )
if __name__ == ' _ _ main _ _ ' :
	arr = [ 0 , 4 , 2 , 5 , 2 , 1 ]
	jump = [ 0 , 1 , 2 , 3 , 1 , 2 ]
	N = len ( arr )
	minJumps ( arr , jump , N - 1 )