Find integral points with minimum distance from given set of integers using BFS | Function to find points at minimum distance ; Hash to store points that are encountered ; Queue to store initial set of points ; List to store integral points ; Using bfs to visit nearest points from already visited points ; Get first element from queue ; Check if ( x - 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x - 1 ) into queue ; Push ( x - 1 ) as new element ; Decrement counter by 1 ; Check if ( x + 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x + 1 ) into queue ; Push ( x + 1 ) as new element ; Decrement counter by 1 ; Print result array ; Driver code
function minDistancePoints ( A , K , n ) { let m = new Map ( ) ; let q = [ ] ; for ( let i = 0 ; i < n ; ++ i ) { m . set ( A [ i ] , true ) ; q . push ( A [ i ] ) ; } let ans = [ ] ; while ( K > 0 ) { let x = q . shift ( ) ; if ( ! m . has ( x - 1 ) && K > 0 ) { m . set ( x - 1 , true ) ; q . push ( x - 1 ) ; ans . push ( x - 1 ) ; K -- ; } if ( ! m . has ( x + 1 ) && K > 0 ) { m . set ( x + 1 , true ) ; q . push ( x + 1 ) ; ans . push ( x + 1 ) ; K -- ; } } for ( let i = 0 ; i < ans . length ; i ++ ) document . write ( ans [ i ] + " " ) ; } let A = [ - 1 , 4 , 6 ] ; let K = 3 ; let n = A . length ; minDistancePoints ( A , K , n ) ;