Magical Indices in an array | Function to count number of magical indices . ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code
< ? php function solve ( $ A , $ n ) { $ i = 0 ; $ cnt = 0 ; $ j = 0 ; $ parent = array ( ) ; $ vis = array ( ) ; for ( $ i = 0 ; $ i < $ n + 1 ; $ i ++ ) { $ parent [ $ i ] = -1 ; $ vis [ $ i ] = 0 ; } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ j = $ i ; if ( $ parent [ $ j ] == -1 ) { while ( $ parent [ $ j ] == -1 ) { $ parent [ $ j ] = $ i ; $ j = ( $ j + $ A [ $ j ] + 1 ) % $ n ; } if ( $ parent [ $ j ] == $ i ) { while ( $ vis [ $ j ] == 0 ) { $ vis [ $ j ] = 1 ; $ cnt ++ ; $ j = ( $ j + $ A [ $ j ] + 1 ) % $ n ; } } } } return $ cnt ; } $ A = array ( 0 , 0 , 0 , 2 ) ; $ n = count ( $ A ) ; echo ( solve ( $ A , $ n ) ) ; ? >