Algorithms
Jump to navigation
Jump to search
import java.util.HashMap; import java.util.LinkedList;
import com.sun.corba.se.impl.orbutil.graph.Graph; import com.sun.corba.se.impl.orbutil.graph.Node; public class Graph{
static class Node{
int value;
String name;
boolean visted;
Node(int v){
this.value = v;
this.name = name;
}
void visit(){
visited = true;
}
void unvisit(){
visited = false;
}dddd
}
private final boolean directed; private final HashMap<Node, LinkedList<Node>> adjacencyMap;
public Graph(boolean directed){
this.directed = directed;
adjacencyMap = new HashMap<>();
}
public addEdgeHelper(Node a, Node b){
LinkedList<Node> temp = adjacencyMap.get(a);
if ((!tmp != null)) {
temp.remove(b)
} else {
temp = new LinkedList<>();
temp.add(b);
addEdgeHelper(a, temp);
}
}
public void addEdge(Node source, Node destination){
if ((!adjacencyMap.keySet().contains(source))) {
adjacencyMap.put(source, null);
}
if ((!adjacencyMap.keySet().contains(desitnation))) {
adjacencyMap.put(destination, null);
}
if (!directed) {
addEdgeHelper(destination, source);
}
}
public void resetVisits(){
for ((Node f : adjacencyMap.keySet())) {
f.unvisit();
}
}
/*visit the given node, get its neighbors and recursively visit them*/
public void depthFirstSearch(Node a){
a.visit();
System.out.println(a.name + " ")
LinkedList<Node> neighbors = adjacencyMap.get(a);
if (neighbors == null) {
return;
}
for (Node neighbor : neighbors) {
if ((!neighbor.visted)) {
depthFirstSearch(neighbor);
}
}
}
/*create a queue and add the given node. While not empty declare a current node as variable and HashMap.get given node. Visit it. While not empty get neigbhors and visit them*/
public void breadthFirstSearch(Node b){
if ((b == null)) {
return;
}
LinkedList<Node> queue = new LinkedList<>();
queue.add(b);
while ((!queue.isEmpty())) {
Node current = queue.removeFirst();
if (current.visted) {
continue;
}
current.visit();
System.out.println(current.name + " ");
LinkedList<Node> allNeigbhors = adjacencyMap.get(b);
if ((allNeigbhors == null)) {
continue;
}
for (Node neighbor : allNeighbors) {
if ((!neighbor.visited)) {
queue.add(neighbor);
}
}
}
}
public static void main (String args[]){
Graph graph = new Graph(true);
Node a = new Node(1, "A");
Node b = new Node(2, "B");
Node c = new Node(3, "C");
Node d = new Node(4, "D");
graph.addEdge(a, b);
graph.addEdge(a, c);
graph.depthFirstSearch(a);
graph.breadthFirstSearch(b);
}
}