A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.
Implementing the graph, and should include the following methods:
write a function called breadthFirst that takes in a node as an argument and returns A collection of nodes in the order they were visited.
complexity:
time: O(n^2)
space: O(n)
Graph graph = new Graph();
Node n1 = new Node("A");
Node n2 = new Node("B");
Node n3 = new Node("C");
Node n4 = new Node("D");
graph.addNode(n1);
graph.addNode(n2);
graph.addNode(n3);
graph.addNode(n4);
graph.addEdge(n1,n2);
graph.addEdge(n1,n3);
graph.addEdge(n1,n4);
graph.breadthFirst(n1)
output: [A, B, C, D]
DFS (Depth-first search) is technique used for traversing tree or graph. … In this traversal first the deepest node is visited and then backtracks to it’s parent node if no sibling of that node exist.
write a function called depthFirst that takes in a node as an argument and returns collection of nodes in their pre-order depth-first traversal order.
complexity:
time: O(n^2)
space: O(n)