|
| 1 | +import java.util.*; |
| 2 | +class Graph{ |
| 3 | + |
| 4 | + static HashMap<String,List<Node>> adj; //creating a adjacency List {source ->destinations} |
| 5 | + |
| 6 | + public Graph(){ |
| 7 | + this.adj=new HashMap<>(); //constructor initializes the adjacency list |
| 8 | + } |
| 9 | + |
| 10 | + static class Node{ //Node class to store the destination place and the distance frome source to destination |
| 11 | + String dest; |
| 12 | + int dist; |
| 13 | + |
| 14 | + Node(String dest,int dist){ |
| 15 | + this.dest=dest; |
| 16 | + this.dist=dist; |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + public static void insert(String src,String dest,int dist){ |
| 21 | + insert(src,new Node(dest,dist)); //Undirected weighted graph |
| 22 | + insert(dest,new Node(src,dist)); |
| 23 | + } |
| 24 | + |
| 25 | + private static void insert(String src,Node n){ |
| 26 | + if(adj.isEmpty() || !adj.containsKey(src)){ |
| 27 | + adj.put(src,new ArrayList<>()); |
| 28 | + } |
| 29 | + adj.get(src).add(n); |
| 30 | + } |
| 31 | + |
| 32 | + public static void BFS(String src){ // BREADTH-FIRST-SEARCH |
| 33 | + if(adj.isEmpty()) return; |
| 34 | + |
| 35 | + HashSet<String> set=new HashSet<>(); |
| 36 | + Queue<String> q=new LinkedList<>(); |
| 37 | + q.offer(src); |
| 38 | + set.add(src); |
| 39 | + |
| 40 | + while(!q.isEmpty()){ |
| 41 | + String node=q.poll(); |
| 42 | + System.out.print(node+" "); |
| 43 | + List<Node> neighbours=adj.get(src); |
| 44 | + if(neighbours!=null){ |
| 45 | + for(Node neighbour:neighbours){ |
| 46 | + if(neighbour!=null && !set.contains(neighbour.dest)){ |
| 47 | + q.offer(neighbour.dest); |
| 48 | + set.add(neighbour.dest); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | +} |
| 56 | + |
| 57 | +class Main{ |
| 58 | + public static void main(String[] args){ |
| 59 | + Graph graph=new Graph(); //instantiating Graph by making an object graph of GRAPH |
| 60 | + graph.insert("DELHI","MUMBAI",990); |
| 61 | + graph.insert("MUMBAI","PUNE",100); |
| 62 | + graph.insert("PUNE","GOA",140); |
| 63 | + graph.insert("BANGALORE","PUNE",453); |
| 64 | + graph.insert("DELHI","PUNE",1056); |
| 65 | + graph.insert("DELHI","HYDERABAD",1099); |
| 66 | + graph.insert("VISHAKHAPATNAM","HYDERABAD",230); |
| 67 | + graph.insert("BANGALORE","DELHI",1000); |
| 68 | + graph.insert("CHENNAI","BANGALORE",600); |
| 69 | + graph.insert("CHENNAI","DELHI",1300); |
| 70 | + |
| 71 | + graph.BFS("DELHI"); |
| 72 | + } |
| 73 | +} |
0 commit comments