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