forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.java
More file actions
47 lines (39 loc) · 1.01 KB
/
BFS.java
File metadata and controls
47 lines (39 loc) · 1.01 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
package algoexpert.medium;
import java.util.*;
/*
PROBLEM:
Implement Breadth First Search
-> time : O(v+e) | space : O(v)
*/
public class BFS
{
static class Node
{
String name;
ArrayList<Node> children = new ArrayList<Node>();
public Node(String name)
{
this.name = name;
}
// time : O(v+e) | space : O(v)
public ArrayList<String> breadthFirstSearch(ArrayList<String> array)
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(this);
while(queue.size() > 0)
{
Node current = queue.remove();
array.add(current.name);
for(int i = 0; i < current.children.size(); i++)
{ queue.add(current.children.get(i)); }
}
return array;
}
public Node addChild(String name)
{
Node child = new Node(name);
children.add(child);
return this;
}
}
}