Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Queue;
- import java.util.Scanner;
- class Node {
- int data;
- boolean visited;
- List<Node> neighbours;
- Node(int data) {
- this.data = data;
- this.neighbours = new ArrayList<>();
- }
- public void addneighbours(Node neighbourNode) {
- this.neighbours.add(neighbourNode);
- }
- public List<Node> getNeighbours() {
- return neighbours;
- }
- public void setNeighbours(List<Node> neighbours) {
- this.neighbours = neighbours;
- }
- }
- class BreadthFirstSearch {
- private Queue<Node> queue;
- static ArrayList<Node> nodes = new ArrayList<Node>();
- public BreadthFirstSearch() {
- queue = new LinkedList<Node>();
- }
- public void bfs(Node node) {
- //Lengkapi
- queue.add(node);
- node.visited = true;
- while (!queue.isEmpty()){
- Node isi = queue.remove();
- System.out.print(isi.data + " ");
- List<Node> neighbours = isi.getNeighbours();
- int i = 0;
- while (i < neighbours.size()){
- Node check = neighbours.get(i);
- if(check != null && !check.visited){
- queue.add(check);
- check.visited = true;
- }
- i++;
- }
- }
- }
- public void bfs(Node[] nodes, int mulai){
- for (int i = 0; i < nodes.length; i++) {
- if (nodes[i].data == mulai) {
- bfs(nodes[i]);
- break;
- }
- }
- System.out.println("");
- }
- }
- public class BFSMain {
- public static void main(String arg[]) {
- Scanner in = new Scanner(System.in);
- BreadthFirstSearch BFS = new BreadthFirstSearch();
- String input[] = in.nextLine().split(" ");
- Node[] nodes = new Node[input.length];
- for (int i = 0; i < input.length; i++) {
- nodes[i] = new Node(Integer.parseInt(input[i]));
- }
- int n = in.nextInt();
- for (int i = 0; i < n; i++) {
- int A = in.nextInt();
- int B = in.nextInt();
- nodes = addneighbour(nodes, A, B);
- }
- int mulai = in.nextInt();
- BFS.bfs(nodes, mulai);
- }
- public static Node[] addneighbour(Node[] nodes, int A, int B){
- for (int i = 0; i < nodes.length; i++) {
- if (nodes[i].data==A) {
- for (int j = 0; j < nodes.length; j++) {
- if (nodes[j].data==B) {
- nodes[i].addneighbours(nodes[j]);
- }
- }
- }
- }
- return nodes;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement