Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.*;
- public class Main {
- private static Object[] BFS(Node goal, Node start) {
- Queue<Node> q = new ArrayDeque<>();
- ArrayList<Node> discovered = new ArrayList<>();
- q.add(start);
- while(!q.isEmpty()) {
- Node v = q.poll();
- discovered.add(v);
- if(v == goal) {
- return discovered.toArray();
- }
- for (Node neighbor:
- v.getNeighbors()) {
- q.add(neighbor);
- }
- }
- return discovered.toArray();
- }
- public static void main(String[] args) {
- // write your code here
- Node root = new Node(0);
- Node child1 = new Node(1);
- Node child2 = new Node(2);
- Node grandchild = new Node(3);
- root.addNeighbor(child1);
- root.addNeighbor(child2);
- child2.addNeighbor(grandchild);
- for (Object v:
- BFS(grandchild, root)) {
- Node casted = (Node)v;
- System.out.print(casted.getValue() + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement