import java.util.*;
public class BFS {
public BFS() {
}
void addEdge(ArrayList<ArrayList<Integer>> adj, int v, int u){
adj.get(v).add(u);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<4;i++){
adj.add(new ArrayList<>());
}
BFS g = new BFS();
g.addEdge(adj,0, 1);
g.addEdge(adj,0, 2);
g.addEdge(adj,1, 2);
g.addEdge(adj,2, 0);
g.addEdge(adj,2, 3);
g.addEdge(adj,3, 3);
g.BFS(2,adj);
}
void BFS(int v,ArrayList<ArrayList<Integer>> adj){
LinkedList<Integer> queue = new LinkedList<>();
queue.add(v);
boolean[] visited = new boolean[adj.size()];
visited[v]=true;
while (!queue.isEmpty()){
Integer val = queue.poll();
System.out.println(val);
ArrayList<Integer> list = adj.get(val);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
Integer i = iterator.next();
if(!visited[i]){
visited[i] = true;
queue.add(i);
}
}
}
}
}
public class BFS {
public BFS() {
}
void addEdge(ArrayList<ArrayList<Integer>> adj, int v, int u){
adj.get(v).add(u);
}
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<4;i++){
adj.add(new ArrayList<>());
}
BFS g = new BFS();
g.addEdge(adj,0, 1);
g.addEdge(adj,0, 2);
g.addEdge(adj,1, 2);
g.addEdge(adj,2, 0);
g.addEdge(adj,2, 3);
g.addEdge(adj,3, 3);
g.BFS(2,adj);
}
void BFS(int v,ArrayList<ArrayList<Integer>> adj){
LinkedList<Integer> queue = new LinkedList<>();
queue.add(v);
boolean[] visited = new boolean[adj.size()];
visited[v]=true;
while (!queue.isEmpty()){
Integer val = queue.poll();
System.out.println(val);
ArrayList<Integer> list = adj.get(val);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
Integer i = iterator.next();
if(!visited[i]){
visited[i] = true;
queue.add(i);
}
}
}
}
}
No comments:
Post a Comment