Find integral points with minimum distance from given set of integers using BFS | Java implementation of above approach ; 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
import java . util . HashMap ; import java . util . LinkedList ; import java . util . Map ; import java . util . Queue ; class Geeks { static void minDistancePoints ( int A [ ] , int K , int n ) { Map < Integer , Boolean > m = new HashMap < Integer , Boolean > ( ) ; Queue < Integer > q = new LinkedList < Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { m . put ( A [ i ] , true ) ; q . add ( A [ i ] ) ; } LinkedList < Integer > ans = new LinkedList < Integer > ( ) ; while ( K > 0 ) { int x = q . poll ( ) ; if ( ! m . containsKey ( x - 1 ) && K > 0 ) { m . put ( x - 1 , true ) ; q . add ( x - 1 ) ; ans . add ( x - 1 ) ; K -- ; } if ( ! m . containsKey ( x + 1 ) && K > 0 ) { m . put ( x + 1 , true ) ; q . add ( x + 1 ) ; ans . add ( x + 1 ) ; K -- ; } } for ( Integer i : ans ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { int A [ ] = new int [ ] { - 1 , 4 , 6 } ; int K = 3 ; int n = A . length ; minDistancePoints ( A , K , n ) ; } }