Shortest path length between two given nodes such that adjacent nodes are at bit difference 2 | Function to count set bits in a number ; Stores count of set bits in xo ; Iterate over each bits of xo ; If current bit of xo is 1 ; Update count ; Update xo ; Function to find length of shortest path between the nodes a and b ; Stores XOR of a and b ; Stores the count of set bits in xorVal ; If cnt is an even number ; Driver Code ; Given N ; Given a and b ; Function call
def countbitdiff ( xo ) : NEW_LINE INDENT count = 0 NEW_LINE while ( xo ) : NEW_LINE INDENT if ( xo % 2 == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT xo = xo // 2 NEW_LINE DEDENT return count NEW_LINE DEDENT def shortestPath ( n , a , b ) : NEW_LINE INDENT xorVal = a ^ b NEW_LINE cnt = countbitdiff ( xorVal ) NEW_LINE if ( cnt % 2 == 0 ) : NEW_LINE INDENT print ( cnt // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 NEW_LINE a , b = 15 , 3 NEW_LINE shortestPath ( n , a , b ) NEW_LINE DEDENT